跟進問題,這個問題使用||在Rails的案例開關在包裝方法
Using || in Case switch in Rails
我的問題是應該怎樣包裹時,當在一個方法,使代碼更易讀來完成。直接返回它,因爲你會寫它不適合我?
實施例:
case @page_title
when "Log in", "Forgot Your Password", "Create a New Password" then #...
我想:
case @page_title
when unprotected then #...
根據答案我的解決方案下面將是(如果使用和ELSIF代替)
代碼之前(開關) :
case stats_category.unit
when StatsCategory::UNITS::SAME_AS_NAME_INTEGER, StatsCategory::UNITS::SECONDS
if !is_integer
@error = true
@message = ""
else
write_attribute(:data,value)
end
when StatsCategory::UNITS::KILOMETERS, StatsCategory::UNITS::SAME_AS_NAME_DECIMAL
if !is_float
@error = true
@message = ""
else
write_attribute(:data,value)
end
when StatsCategory::UNITS::HH_MM_SS
if !is_HH_MM_SS
@error = true
@message = ""
else
write_attribute(:data,value.split(":").sum)
end
end
編碼a refte(if,elsif):
category_unit = stats_category.unit
if integer_unit(category_unit)
if !is_integer
@error = true
@message = ""
else
write_attribute(:data,value)
end
elsif float_unit(category_unit)
if !is_float
@error = true
@message = ""
else
write_attribute(:data,value)
end
elsif time_format_HH_MM_SS(category_unit)
if !is_HH_MM_SS
@error = true
@message = ""
else
write_attribute(:data,value.split(":").sum)
end
else
end
def integer_unit(unit)
unit === StatsCategory::UNITS::SAME_AS_NAME_INTEGER || unit === StatsCategory::UNITS::SECONDS
end
def float_unit(unit)
unit === StatsCategory::UNITS::KILOMETERS || unit === StatsCategory::UNITS::SAME_AS_NAME_DECIMAL
end
def time_format_HH_MM_SS(unit)
unit === StatsCategory::UNITS::HH_MM_SS
end
找到了答案。根據塞爾吉奧Tulentsev
交換機提供的解決方案我的代碼:
case stats_category.unit
when *integer_unit
if !is_integer
@error = true
@message = ""
else
write_attribute(:data,value)
end
when *float_unit
if !is_float
@error = true
@message = ""
else
write_attribute(:data,value)
end
when *time_format_HH_MM_SS
if !is_HH_MM_SS
@error = true
@message = ""
else
write_attribute(:data,value.split(":").sum)
end
end
方法:
def integer_unit
[StatsCategory::UNITS::SAME_AS_NAME_INTEGER, StatsCategory::UNITS::SECONDS]
end
def float_unit
[StatsCategory::UNITS::KILOMETERS, StatsCategory::UNITS::SAME_AS_NAME_DECIMAL]
end
def time_format_HH_MM_SS
[StatsCategory::UNITS::HH_MM_SS]
end
請顯示不能正常工作的代碼。 – mudasobwa
增加了一個例子,檢查這是你的意思 – Leventix
@Leventix什麼是'無保護'? – Stefan