次のコードがあります。
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 は代わりにそれを「偽である」と言います)。 false
nil
false
nil
とにかく、return unless nil
プレーンと同じですreturn
。
明示的なステートメントshow_msg
がないメソッドreturn
は、最後のステートメントの値を返します。そのステートメントはputs
、 を返すnil
です。Soshow_msg
も を返しますnil
。nil
は偽であるため、 に到達and
する前に短絡しreturn
ます。したがって、return
は実行されず、Ruby は次の行に進んで実行します。