39

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,289
  • 1
  • 29
  • 40

3 Answers3

60

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,289
  • 1
  • 29
  • 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
  • 8
    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
8

Possible since Ruby 2.3.

dog&.owner&.phone
Jacka
  • 1,880
  • 4
  • 23
  • 32
  • 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,744
  • 2
  • 18
  • 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