43

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'
Alistair A. Israel
  • 6,417
  • 1
  • 31
  • 40

3 Answers3

64

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

Alistair A. Israel
  • 6,417
  • 1
  • 31
  • 40
  • 4
    Alternatively, if you're doing something like `@params = @params || 5 `you can shorten it to `@params ||= 5` – Ryan Bigg Oct 19 '11 at 02:58
  • 3
    @RyanBigg: To be pedantic, it's more like `@params || @params = 5`. http://stackoverflow.com/questions/995593/what-does-mean-in-ruby/2505285#2505285 – Andrew Grimm Oct 19 '11 at 03:58
  • 10
    This is sadly not entirely true. Kotlin's `?:` and C#'s `??` check for NULLITY. Ruby's `||` checks for truth-iness. If you are working with booleans, let's say `foo = bar || true` and you are expecting `true` to be the default only if `bar` is `nil`, it won't work. If `bar` is not `nil` but `false`, it will still default to `true`. – Adeynack May 06 '19 at 12:30
9

Possible since Ruby 2.3.

dog&.owner&.phone
Jacka
  • 2,270
  • 4
  • 27
  • 34
  • 1
    It solves a different problem, but this gets around the `null`-ity vs `true`-thy conundrum:, `nil.class # => NilClass`, `nil&.class # => nil (not NilClass!)`, `false.class #=> FalseClass`, `false&.class #=> FalseClass` – Alistair A. Israel Sep 11 '20 at 16:44
4

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

Hock
  • 5,784
  • 2
  • 19
  • 25
  • Check [this comment](https://stackoverflow.com/questions/7816032/ruby-equivalent-of-groovys-elvis-operator#comment98655983_7816041). It's not exactly the same. – Adeynack May 06 '19 at 12:30
  • 1
    @Adeynack, it seems like both syntaxes @Hock mentioned would branch based on the truthiness of `ARGV[0]`. If I'm wrong, can you explain which one would not and why? – JakeRobb Sep 09 '22 at 21:02
  • 1
    @JakeRobb, you are totally right and I am now wondering why I wrote that 3 years ago. Thanks for getting the confusion I introduced out! – Adeynack Sep 14 '22 at 07:56