Ruby 没有目标对象的大小写表达式:应该使用它吗?
我知道您可以在没有目标对象的情况下使用case语句,如下所示:Ruby 没有目标对象的大小写表达式:应该使用它吗?,ruby,syntax,Ruby,Syntax,我知道您可以在没有目标对象的情况下使用case语句,如下所示: case when condition1 do_something1 when condition2 do_something2 else do_something_else end 这相当于: if condition1 do_something1 elsif condition2 do_something2 else do_something_else end 是否有任何理由允许在没有目标对象的情况
case
when condition1
do_something1
when condition2
do_something2
else
do_something_else
end
这相当于:
if condition1
do_something1
elsif condition2
do_something2
else
do_something_else
end
是否有任何理由允许在没有目标对象的情况下使用case表达式?是否存在这样使用大小写表达式的情况?它可用于检查多个表达式。考虑这个例子:
print "Enter first string: "
some_string = gets.chomp
print "Enter second string: "
some_string1 = gets.chomp
puts case
when some_string.match(/\d/)
'String has numbers'
when some_string1.match(/[a-zA-Z]/)
'String has letters'
else
'String has no numbers or letters'
end
在这里,您必须检查两个不同的变量。也许专家们有一些不同的观点。实际上没有区别,一个空的
案例
语句不会调用==
,因为没有什么可以调用的。例如:
class CaseExample
def ===(other)
puts "received #{other}"
super(other)
end
end
当这样称呼时:
case
when CaseExample.new()
puts "got here"
end
将打印:
"got here"
"received me"
而:
case "me"
when CaseExample.new()
puts "got here"
end
它将打印:
"got here"
"received me"
如果没有case对象,我宁愿选择
if/elsif
,因为意图会更清楚。我不确定我是否理解这个问题,没有值表达式,这是默认情况(就像在类似C的语言中看到的那样)。