1

次のコードがあります。

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

なんで?

4

2 に答える 2

3

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
于 2012-10-31T01:19:21.043 に答える
3

unless nil;で何をしようとしているのかわかりません。nil真の値になることは決してないため、これはノーオペレーションです。(Ruby では、はブール真偽テストのコンテキストで偽と見なされる、それ自体nil以外の 1 つの値です。 と等しくない場合に「偽である」と言うのは混乱を招くため、Rubyist は代わりにそれを「偽である」と言います)。 falsenilfalsenil

とにかく、return unless nilプレーンと同じですreturn

明示的なステートメントshow_msgがないメソッドreturnは、最後のステートメントの値を返します。そのステートメントはputs、 を返すnilです。Soshow_msgも を返しますnilnilは偽であるため、 に到達andする前に短絡しreturnます。したがって、returnは実行されず、Ruby は次の行に進んで実行します。

于 2012-10-31T01:24:50.513 に答える