跟进问题,这个问题使用||在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