I’m pretty new to Ruby and Rails but even after searching stack overflow and google I couldn’t find an answer to this.
I’ve got a simple Ruby shorthand if statement that should return an integer like so:
# in the context of this erb document `amount` is defined as 5.
@c = ( defined? amount ? amount : r( 1,4 ) )
r() is a custom helper function that returns a random number between in this case 1 and 4.
The way I intend this to work is that if amount is defined, then use the number defined as amount, else generate a random number between 1 and 4 and use that instead.
When printing out @c however Ruby outputs expression rather than a number.
What do I have to do to get this working as I intended and what am I doing wrong?
Many thanks for reading!
defined?is binding toamount ? amount : r(1,4)so it is equivalent to:You probably want:
Actually, odds are that
amount || r(1,4), oramount.nil? ? r(1,4) : amountwould better match what you want, since I think you don’t want this:…in which case
@cwould benil– the value of the defined variable.