次のコードがあります。
def test
show_msg and return unless nil
puts "This line can not be executed"
end
def show_msg
puts "exit here"
end
test
出力:
exit here
This line can not be executed
私は唯一のオンラインを期待していました:
exit here
なんで?
次のコードがあります。
def test
show_msg and return unless nil
puts "This line can not be executed"
end
def show_msg
puts "exit here"
end
test
出力:
exit here
This line can not be executed
私は唯一のオンラインを期待していました:
exit here
なんで?
as said in the comments, this doesn't work because puts actually returns nil, so you can either explictly return something from your show_msg function, or either use p for instance
def test
show_msg and return unless nil
puts "This line can not be executed"
end
def show_msg
p "exit here"
end
test
unless nil;で何をしようとしているのかわかりません。nil真の値になることは決してないため、これはノーオペレーションです。(Ruby では、はブール真偽テストのコンテキストで偽と見なされる、それ自体nil以外の 1 つの値です。 と等しくない場合に「偽である」と言うのは混乱を招くため、Rubyist は代わりにそれを「偽である」と言います)。 falsenilfalsenil
とにかく、return unless nilプレーンと同じですreturn。
明示的なステートメントshow_msgがないメソッドreturnは、最後のステートメントの値を返します。そのステートメントはputs、 を返すnilです。Soshow_msgも を返しますnil。nilは偽であるため、 に到達andする前に短絡しreturnます。したがって、returnは実行されず、Ruby は次の行に進んで実行します。