How to find a hash key containing a matching value
You could use Enumerable#select:
clients.select{|key, hash| hash["client_id"] == "2180" }
#=> [["orange", {"client_id"=>"2180"}]]
Note that the result will be an array of all the matching values, where each is an array of the key and value.
Working with Hashes that have a default value
0 will be the fallback if you try to access a key in the hash that doesn't exist
For example:
count = Hash.new
-> count['key'] => nil
vs
count = Hash.new(0)
-> count['key'] => 0
Ruby: Creating a hash key and value from a variable in Ruby
If you want to populate a new hash with certain values, you can pass them to Hash::[]
:
Hash["a", 100, "b", 200] #=> {"a"=>100, "b"=>200}
Hash[ [ ["a", 100], ["b", 200] ] ] #=> {"a"=>100, "b"=>200}
Hash["a" => 100, "b" => 200] #=> {"a"=>100, "b"=>200}
So in your case:
Hash[id, 'foo']
Hash[[[id, 'foo']]]
Hash[id => 'foo']
The last syntax id => 'foo'
can also be used with {}
:
{ id => 'foo' }
Otherwise, if the hash already exists, use Hash#=[]
:
h = {}
h[id] = 'foo'
Storing a function in the value for a key within a hash
You can use the send keyword
send h[step]
since you writing the method name directly in value part of the hash, the call is being made, but If you store the method names as a string and then if you call by send method as shown below, it would work.
def hi
puts 'hi'
end
def hello
puts 'hello'
end
h = {
1 => 'hi',
2 => 'hello',
}
send h[1]
Get key value pair of hash for the given key , in ruby
There is a method, Hash#assoc can do similar things. But it returns the key and value in an array, which you can easily change it into a hash.
And an alternative is use Hash#select, which does return a hash according to the block given.
h1 = { "fish" => "aquatic animal", "tiger" => "big cat" }
h1.assoc "fish" # ["fish", "aquatic animal"]
h1.select { |k,v| k == "fish" } # {"fish"=>"aquatic animal"}
How to check if a specific key is present in a hash or not?
Hash
's key?
method tells you whether a given key is present or not.
session.key?("user")
Method to get value from a hash from array of keys in Ruby
[:font_size].inject(my_hash){|h, k| h.to_h[k]} #=> 10
[:boo, :name].inject(my_hash){|h, k| h.to_h[k]} #=> "blah"
[:boo, :foo].inject(my_hash){|h, k| h.to_h[k]} #=> nil
How to check if specific value is present in a hash?
Hash includes Enumerable, so you can use the many methods on that module to traverse the hash. It also has this handy method:
hash.has_value?(value_you_seek)
To find the key associated with that value:
hash.key(value_you_seek)
This API documentation for Ruby (1.9.2) should be helpful.
Ruby how to find each value in hash greater than x?
You can use:
months.select { |_month, days| days > 30 }
This former gives you all results that fit the criteria (days > 30
).
Here are the docs:
select
Once you've got the values you need, you can then print them to the console (or output however you'd like), e.g.
long_months = months.select { |_month, days| days > 30 }
long_months.each { |month, days| puts "#{month} has #{days} days" }
All that being said, assigning to a value before printing the result means two loops, whereas this can be achieved in one using a simple each
:
months.each do |month, days|
puts("#{month} has #{days} days") if days > 30
end
That'll be more efficient as there's less churn involved :)
Related Topics
How to See the Dependency Tree Just from Gemfile
Rails 6.1, Ruby 3.0.0: Tests Error as They Cannot Load Rexml
Error While Installing Ruby Using Rvm
Can Bundler Show Me Which Gems in Gemfile Have Newer Versions (Eg. Dry-Run of Bundle Update)
In Ruby, How to Check If Method "Foo=()" Is Defined
Changing Field Separator/Delimiter in Exported CSV Using Ruby CSV
Accessing Objects Memory Address in Ruby
Ruby Bundler Multiple Sources in Gemfile
Install Ruby Curb Gem in Windows Xp
Passenger: Internal Server Error
How to Get the Target of a Symlink
How to Get a Stack Trace Object in Ruby
Repairing Postgresql After Upgrade to Osx Mavericks
Ruby Rails - Select Only Few Columns from the Data Base