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 is matched:
hash = {
:key1 => value1,
:key2 => value2, # This key2\value2 pair should be added only 'if condition' is 'true'
:key3 => value3,
...
}
How can I do that and keep a "good" readability for the code? Am I "forced" to use the merge method?
I prefer tap, as I think it provides a cleaner solution than the ones described here by not requiring any hacky deleting of elements and by clearly defining the scope in which the hash is being built.
It also means you don't need to declare an unnecessary local variable, which I always hate.
In case you haven't come across it before, tap is very simple - it's a method on Object that accepts a block and always returns the object it was called on. So to build up a hash conditionally you could do this:
Hash.new.tap do |my_hash|
my_hash[:x] = 1 if condition_1
my_hash[:y] = 2 if condition_2
...
end
There are many interesting uses for tap, this is just one.
A functional approach with Hash.compact:
hash = {
:key1 => 1,
:key2 => (2 if condition),
:key3 => 3,
}.compact
Probably best to keep it simple if you're concerned about readability:
hash = {}
hash[:key1] = value1
hash[:key2] = value2 if condition?
hash[:key3] = value3
...
Keep it simple:
hash = {
key1: value1,
key3: value3,
}
hash[:key2] = value2 if condition
This way you also visually separate your special case, which might get unnoticed if it is buried within hash literal assignment.
I use merge and the ternary operator for that situation,
hash = {
:key1 => value1,
:key3 => value3,
...
}.merge(condition ? {:key2 => value2} : {})
Simple as this:
hash = {
:key1 => value1,
**(condition ? {key2: value2} : {})
}
Hope it helps!
IF you build hash from some kind of Enumerable data, you can use inject, for example:
raw_data.inject({}){ |a,e| a[e.name] = e.value if expr; a }
In case you want to add few keys under single condition, you can use merge:
hash = {
:key1 => value1,
:key2 => value2,
:key3 => value3
}
if condition
hash.merge!(
:key5 => value4,
:key5 => value5,
:key6 => value6
)
end
hash
First build your hash thusly:
hash = {
:key1 => value1,
:key2 => condition ? value2 : :delete_me,
:key3 => value3
}
Then do this after building your hash:
hash.delete_if {|_, v| v == :delete_me}
Unless your hash is frozen or otherwise immutable, this would effectively only keep values that are present.
Using fetch can be useful if you're populating a hash from optional attributes somewhere else. Look at this example:
def create_watchable_data(attrs = {})
return WatchableData.new({
id: attrs.fetch(:id, '/catalog/titles/breaking_bad_2_737'),
titles: attrs.fetch(:titles, ['737']),
url: attrs.fetch(:url, 'http://www.netflix.com/shows/breaking_bad/3423432'),
year: attrs.fetch(:year, '1993'),
watchable_type: attrs.fetch(:watchable_type, 'Show'),
season_title: attrs.fetch(:season_title, 'Season 2'),
show_title: attrs.fetch(:id, 'Breaking Bad')
})
end
Same idea as Chris Jester-Young, with a slight readability trick
def cond(x)
condition ? x : :delete_me
end
hash = {
:key1 => value1,
:key2 => cond(value2),
:key3 => value3
}
and then postprocess to remove the :delete_me entries
Related
I have a hash:
test = {
:key1 => "Test",
:key2 => "Test2",
:key3 => REF TO KEY1
}
Is it possible to let key3 refer to the key1 value?
Yes, this is easily possible. The expression for the value can be any arbitrary Ruby expression, including of course accessing a value from a Hash:
test = {
:key1 => "Test",
:key2 => "Test2",
}
test[:key3] = test[:key1]
This is really not recommended and my guess is that there is a better way to solve whatever larger problem you are attempting to solve with this technique.
But one way you could do this is by creating a Hash whose default_proc returns the value of :key1 if it is passed :key3.
> test = Hash.new { |h,k| k == :key3 ? h[:key1] : nil }
> test[:key1] = "Test"
> puts test[:key3]
Test
And this acts as a reference as can be seen if we modify the value of :key1
> test[:key1] = "Test2"
> puts test[:key3]
Test2
I am a newbie programmer using Ruby, and this is my first question on Stack Overflow so please bear with me. Let's say I have two Hashes:
hash_one = { :key1 => :value1, :key2 => :value2, :key3 => :value3 }
hash_two = { :key4 => :value4, :key5 => :value5, :key6 => :value6 }
What would be the easiest way to move a key/value pair from hash_one (e.g. :key1 => :value1) into hash_two?
hash_two[:key1] = hash_one.delete(:key1)
delete removes key1 from hash_one and returns the value of key1. That value is taken as the parameter to set this key in hash_two.
I have a hash like
{:key1 => "value1", :key2 => "value2"}
And I have a variable k which will have the value as 'key1' or 'key2'.
I want to get the value of k into a variable v.
Is there any way to achieve this with out using if or case? A single line solution is preferred. Please help.
Convert the key from a string to a symbol, and do a lookup in the hash.
hash = {:key1 => "value1", :key2 => "value2"}
k = 'key1'
hash[k.to_sym] # or iow, hash[:key1], which will return "value1"
Rails uses this class called HashWithIndifferentAccess that proves to be very useful in such cases. I know that you've only tagged your question with Ruby, but you could steal the implementation of this class from Rails' source to avoid string to symbol and symbol to string conversions throughout your codebase. It makes the value accessible by using a symbol or a string as a key.
hash = HashWithIndifferentAccess.new({:key1 => "value1", :key2 => "value2"})
hash[:key1] # "value1"
hash['key1'] # "value1"
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).
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
}
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
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.
Is there anything like this possible in Ruby:
hash = { :foo => 'bar', :bar => lambda{ condition ? return 'value1' : return 'value2'}}
That actual code doesn't work (clearly), and I know I could just do the logic before the hash assignment, but it would be nice to work inside the assignment like this. Is such a thing possible?
You don't need a lambda for that, just this should work:
hash = {
:foo => 'bar',
:bar => condition ? 'value1' : 'value2'
}
Or if you want to use a function result on hash,
hash= {
:foo=> 'foooooo',
:bar=> lambda {
if condition
value1
else
value2
end
}.call
}