2

I'm new to Ruby. Is there a way to do the following?

hash = {
  :key1  => defined? value1 ? value1 : nil, 
  :key2  => defined? value2 ? value2 : nil
}

puts hash[:key1] # outputs: ["expression"]

The above code stores the expression, instead of the value (if it is defined) or nil (if it is not defined).

Panagiotis Panagi
  • 9,927
  • 7
  • 55
  • 103
  • 1
    Could you try to explain a little bit more? I've read your question three times and still don't understand what your problem is. – Benoit Garret Oct 26 '11 at 14:00

3 Answers3

2

d11wtg answer will do. Also, by adding parentheses, the values are stored as expected:

hash = {
  :key1  => (defined? value1) ? value1 : nil, 
  :key2  => (defined? value2) ? value2 : nil
}
Panagiotis Panagi
  • 9,927
  • 7
  • 55
  • 103
1

You're looking for lambda, or Proc.

hash = {
  :key1 => lambda { defined?(value1) ? value1 : nil },
  :key2 => lambda { defined?(value2) ? value1 : nil }
}

hash[:key1].call

http://www.ruby-doc.org/core-1.9.2/Kernel.html#method-i-lambda

d11wtq
  • 34,788
  • 19
  • 120
  • 195
  • Thanks for this. Just found that by adding parenthesis does what I was looking for .... `hash = {:key1 => (defined? value1) ? value1 : nil}` – Panagiotis Panagi Oct 26 '11 at 14:12
0

What exactly do you want to do?

hash[:key].nil?

will return true or false, depending if the key exists. Not sure if that's what you are looking for.

Allan Nørgaard
  • 284
  • 2
  • 11