I've been working on a new project and created a custom method for one
of the models. Nothing major.
I brought up the console in --sandbox mode (also have tried in
standard console), and tried playing with it. To my surprise there
was a problem with the if/elseif conditional. The elseif portion
simply would not work. So I tried a couple commands as so to test the
actual if/elseif integrity like so:
person = "Jim"
if person == "Sally"
puts "Hi Sally"
elseif person == "Jim"
puts "Hi Jim"
end
This returns nil. If I put a final <else> catch it will return that
value. What am I doing wrong?
I've been working on a new project and created a custom method for one
of the models. Nothing major.
I brought up the console in --sandbox mode (also have tried in
standard console), and tried playing with it. To my surprise there
was a problem with the if/elseif conditional. The elseif portion
simply would not work. So I tried a couple commands as so to test the
actual if/elseif integrity like so:
person = "Jim"
if person == "Sally"
puts "Hi Sally"
elseif person == "Jim"
puts "Hi Jim"
end
I assume you've got elsif rather than elseif (which doesn't exist ) or
else if, which isn't the same.
For many the observation that every operation in Ruby returns
something - the primary effect, and it may do something else (a side-
effect) is rather strange. So for example, we want the side-effect
"put the stuff out to the printer" when we invoke puts and usually
don't care about the returned value (nil).
It is pretty important to separate what is returned from what it does.
Sometimes they are the same (almost!), however. So == does indeed
compare two comparable values, and it returns the result of that
comparison (true or false).
Perhaps using elsif instead of elseif will help. But your code makes
no attempt to return a value, so the nil is expected.
If you are planning on returning a value, do something like this:
result = if person == "Somebody"
"foo"
elsif person == "Another"
"else if returned"
else
"no match"
end