Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby equivalent of Groovy's Elvis (?:) operator?

Tags:

ruby

groovy

I know I can live without it, but the question's been bugging me.

Is there a Ruby idiom that's equivalent to Groovy's Elvis operator (?:)?

Essentially, I want to be able to shorten this

PARAM = ARGV[0] ? ARGV[0] : 'default'

Or equivalently

PARAM = 'default' unless PARAM = ARGV[0]

Into something like this

PARAM = ARGV[0] ?: 'default'
like image 398
Alistair A. Israel Avatar asked Oct 19 '11 02:10

Alistair A. Israel


3 Answers

Never mind :-) I just found the answer myself after finding out the name of the operator.

From here:

PARAM = ARGV[0] || 'default'

(Must be 'cause I'm juggling 4 languages right now so I forgot I could do that in the first place.)

like image 103
Alistair A. Israel Avatar answered Oct 20 '22 08:10

Alistair A. Israel


Possible since Ruby 2.3.

dog&.owner&.phone
like image 9
Jacka Avatar answered Oct 20 '22 06:10

Jacka


Isn't PARAM = ARGV[0] ? ARGV[0] : 'default' the same as PARAM = (ARGV[0] || 'default') ?

like image 4
Hock Avatar answered Oct 20 '22 06:10

Hock