Ruby on rails 使用| | in Case switch in rail in method
这一问题的后续问题 我的问题是在方法中包装when时应该做什么,以使代码更具可读性。按你写的那样直接退回对我不起作用 例如:Ruby on rails 使用| | in Case switch in rail in method,ruby-on-rails,ruby,switch-statement,Ruby On Rails,Ruby,Switch Statement,这一问题的后续问题 我的问题是在方法中包装when时应该做什么,以使代码更具可读性。按你写的那样直接退回对我不起作用 例如: case @page_title when "Log in", "Forgot Your Password", "Create a New Password" then #... def unprotected o = Object.new class << o def ===(s) s == 'a' || s == 'b'
case @page_title
when "Log in", "Forgot Your Password", "Create a New Password" then #...
def unprotected
o = Object.new
class << o
def ===(s)
s == 'a' || s == 'b'
end
end
o
end
def test(page_title)
result =
case page_title
when unprotected then 'match'
else 'no match'
end
puts "#{page_title} => #{result}"
end
test 'a' # => match
test 'b' # => match
test 'c' # => no match
我想:
case @page_title
when unprotected then #...
根据下面的答案,我的解决方案是(改用if和elsif)
前代码(开关):
重构后的代码(if,elsif):
找到了答案。我的代码是根据Sergio 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
使用
if
和elsif
而不是案例
可能是最简单的方法
但是case
在幕后使用==
方法,因此您可以定义一个函数,该函数返回一个对象,该对象以您想要的方式响应==
。看看能不能有个主意
例如:
case @page_title
when "Log in", "Forgot Your Password", "Create a New Password" then #...
def unprotected
o = Object.new
class << o
def ===(s)
s == 'a' || s == 'b'
end
end
o
end
def test(page_title)
result =
case page_title
when unprotected then 'match'
else 'no match'
end
puts "#{page_title} => #{result}"
end
test 'a' # => match
test 'b' # => match
test 'c' # => no match
def未受保护
o=Object.new
班级比赛
测试“b”#=>匹配
测试“c”#=>不匹配
您完全可以在这里使用方法。让这些方法返回数组[可能的选项],然后将其显示
def unprotected
["Log in", "Forgot Your Password", "Create a New Password"]
end
def check(page)
case page
when *unprotected then 'unprotected'
else 'protected'
end
end
check('Log in') # => "unprotected"
check('Buy') # => "protected"
请显示不起作用的代码。添加一个示例,检查这是否是您想要的meant@Leventix什么是
未受保护的
?未受保护的方法将返回带有=
方法的对象,如果其参数是上述任一字符串,则返回true
。@Stefan在下面的回答中添加了一个示例