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 catch it will return that
value. What am I doing wrong?
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).
I’m assuming that you’re actually worried about the fact that your
conditional isn’t outputting anything. Unless you’re post was a typo,
you mean to use “elsif” instead of “elseif”…
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
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 catch it will return that
value. What am I doing wrong?
Your code produces an error in all versions of Ruby.
Never use irb like interfaces in any programming language, and you
will avoid a lot of confusion and you will never lose your work and you
won’t have to retype anything. Instead open up a test program and run
your code from the command line.
What does
puts “hello world”
return for you?
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.