Ruby 用简短的方式说;anwer=";这";或答案=”;那";
可能重复:Ruby 用简短的方式说;anwer=";这";或答案=”;那";,ruby,function,expression,Ruby,Function,Expression,可能重复: answer=“this”或answer=“that”很冗长 我希望能够使用一个更像answer=(“this”或that”)的表达式,但我知道我不能在或完成后将(真或假)结果与答案进行比较,所以这不是我想要的。更像a=~[a/c]但是我需要插值。我想你指的是=(相等比较)而不是=(赋值)。如果是这种情况,根据情况,你可以执行以下操作之一: if [this, that].include? answer # or # case answer when this, that
answer=“this”或answer=“that”
很冗长
我希望能够使用一个更像
answer=(“this”或that”)
的表达式,但我知道我不能在或完成后将(真或假)结果与答案进行比较,所以这不是我想要的。更像a=~[a/c]但是我需要插值。我想你指的是=
(相等比较)而不是=
(赋值)。如果是这种情况,根据情况,你可以执行以下操作之一:
if [this, that].include? answer
# or #
case answer
when this, that
# do something
end
当您有多组要检查的选项时,后者更好,而当您只有一组感兴趣的选项时,前者更可读。(我通常会将选项粘贴到一个命名变量中,因此如果正确回答,它会更像。包括?回答。这样它读起来清晰,易于维护。)实际上,这个| |
实际上不会返回TRUE或FALSE。它将返回第一项,除非该项为“FALSE”(false或nil,请注意“”既不是false也不是nil),否则它将返回第二项。因此,以下操作将起作用:
foo = nil
bar = "that"
baz = ""
qux = false
answer = foo || bar # => "that"
answer = bar || foo # => "that"
answer = baz || bar # => ""
answer = foo || qux # => false
answer = qux || foo # => nil
因此,在现实中,您的表达式answer=(“this”或that”)
实际上会起作用,除非它总是计算为“this”,因为“this”不是“false”。您也可以使用正则表达式:
answer = 'this'
true if answer =~ /th[is|at]/
=> true
answer = 'that'
true if answer =~ /th[is|at]/
=> true
answer = 'blah'
true if answer =~ /th[is|at]/
=> nil
哎呀-我误读了answer=“this”
,好像以前的评论被删除了一样。(除非你真的是指平等=
而不是赋值=
),如果你真的是指平等=
这里是我以前的评论恢复:[“这个”,“那个”,“另一个”].include?answer
answer=“this”的测试将始终是正确的,因为它将指定“this”若要回答
并测试答案的存在性,这是真的,请您重新审视您的问题,并对您试图实现的目标给出更好的解释。我闻到过早优化和刮胡子的味道。+1用于案例陈述。我想这是@junky真正想要的。作为偏好,我通常使用|
而不是r比或
,因为它在优先顺序方面的行为更可预测。