I am using Ruby on Rails 3.0.10 and I would like to build an hash key\\value pairs in a conditional way. That is, I would like to add a key and its related value if a condition
A functional approach:
hash = { :key1 => 1, :key2 => (2 if condition), :key3 => 3, }.compact
If Hash.compact is not available in your environment, write .reject { |k, v| v.nil? }
Hash.compact
.reject { |k, v| v.nil? }