tags:

views:

144

answers:

3

Hey,

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

foo['bar'] = nil

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

However, nothing happens? Any thoughts?

+10  A: 

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?
mikej
+1, but as an additional note, in Ruby the one-line `if`, which the asker might have wanted for brevity, can be written `puts 'nil' if foo['bar'].nil?`
Arkku
@Arkku Yep, I will update the answer to include this for completeness.
mikej
+1  A: 
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
Delameko
+2  A: 

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.

shingara
Of course, it may sometimes be desirable to differentiate between nil and false, e.g. here the printed message would be incorrect for false, claiming that it was nil.
Arkku
"nil == false" is misleading because they are not equal. Ruby treats nil as a false conditional test result.
Greg
Yes you right is a little bit too much
shingara