Sri Sri - 28 days ago 7
Ruby Question

get between 0 and 5 if variable is nil in ruby?

Is there an elegant way of achieve the following in ruby way?

x = nil #(sometimes it can be value)

y = 0 || 1 || 2 || 3 || 4

z = x || y #(if x is not nil then x else 0 || 1 || 2 || 3 || 4)


Thanks

Answer

Try something like this:

x = nil
y = [0, 1, 2, 3, 4].cycle
z = x || y.next
#=> 0
z = x || y.next
#=> 1

or just this if you don't want cycling:

x = nil
y = -1
z = x || y = y.next
#=> 0
z = x || y = y.next
#=> 1