Reputation: 34103
def my_method
"Happy New Year"
end
if my_method.class == Integer
...
else
## How would I catch the return value "Happy New Year" and output it here, if the initial condition is not met?
end
(I'm sorry if I abuse the use of classes in my poor example.)
Upvotes: 0
Views: 111
Reputation: 3765
You could do it by creating a variable within the conditional:
def my_method
"Happy New Year"
end
if (x = my_method).class == Integer
# do something
else
puts x
end
#=> "Happy New Year"
This stores the result of the my_method
call to the variable x
, which you can then refer to. Of course, depending on the context in which you'll use this, you should come up with a better variable name than x
.
Upvotes: 4
Reputation: 87516
For easiest reading, just make a local variable on the previous line:
result = my_method
if result.class == Integer
..
else
puts result
end
Upvotes: 2