开发者

Why does this Ruby 'if' not behave as expected?

开发者 https://www.devze.com 2022-12-25 14:12 出处:网络
Im sure I am missing something here but none the less. foo[\'bar\'] = nil if(foo[\'bar\'] == nil) puts \"开发者_JAVA技巧foo bar is nil :(\"

Im sure I am missing something here but none the less.

foo['bar'] = nil

if(foo['bar'] == nil)
   puts "开发者_JAVA技巧foo bar is nil :("

However, nothing happens? Any thoughts?


You need an end statement to close your if i.e.

if(foo['bar'] == nil)
   puts "foo bar is nil :("
end

Note that there is a nil? method for checking if something is nil and the brackets around your condition aren't necessary so it would be more idiomatic Ruby to write:

if foo['bar'].nil?
  puts "foo bar is nil :("
end

As Arkku commented, a single line if can be written concisely as:

puts "foo bar is nil :(" if foo['bar'].nil?

Which is better depends on the context (e.g. do you want to emphasise the condition or emphasise what happens if the condition is true) and a certain amount of personal preference. But as an example you might put a guard condition at the start of a method e.g.

raise "bar needed" if foo['bar'].nil?


nil is treat it exactly like false in a condition. So you don't need test if your variable is really nil.

foo = {}
foo['bar'] = nil
puts "foo bar is nil :(" unless foo['bar']
puts "foo bar is nil :(" if !foo['bar']

In ruby just nil and false return false in condition statement.


irb(main):002:0> foo = {}
=> {}
irb(main):003:0> foo['bar'] = nil
=> nil
irb(main):004:0> foo['bar']
=> nil
irb(main):005:0> if foo['bar'] == nil
irb(main):006:1> puts "foo bar nil"
irb(main):007:1> end
foo bar nil
=> nil
0

精彩评论

暂无评论...
验证码 换一张
取 消