Conditional key/value in hash literal?

12 views
Skip to first unread message

Paul Jungwirth

unread,
May 26, 2016, 10:58:44 PM5/26/16
to pdxruby
This question is a little fussy, but is there any way to embed a
conditional key+value pair inside a hash literal? I want to do
something like this:

{
a: 1,
b: nil,
*(c ? {c: c} : {})
}

Getting either `{a:1, b:nil}` or `{a:1, b:nil, c:c}` but not `{..., c:nil}`.

The analogy is `[*foo, *nil]` giving just `foo`.

Is this possible? If not, what is the nicest way to write it? I can't
just take out everything with a `nil` value, because I want to keep
`b: nil`.

Thanks!
Paul


--
_________________________________
Pulchritudo splendor veritatis.

Paul Jungwirth

unread,
May 26, 2016, 11:14:22 PM5/26/16
to pdxruby
Well after a little more thought I was able to come up with the
magical Google terms, and it turns out Ruby 2.0 introduces a
double-splat operator that does just this!:

http://stackoverflow.com/questions/18289152/what-does-a-double-splat-operator-do

Good night all!
Paul
Reply all
Reply to author
Forward
0 new messages