Alistair A. Israel
Alistair A. Israel

Reputation: 6567

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

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'

Upvotes: 45

Views: 19210

Answers (3)

Jacka
Jacka

Reputation: 2590

Possible since Ruby 2.3.

dog&.owner&.phone

Upvotes: 13

Alistair A. Israel
Alistair A. Israel

Reputation: 6567

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.)

Upvotes: 66

Hock
Hock

Reputation: 5804

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

Upvotes: 4

Related Questions