Access Ruby hash variables
Try request.params["model"]["password"]
A Hash
's keys can consist of both symbols and strings. However, a string key is different than a symbol key.
Note the following:
h = {:name => 'Charles', "name" => 'Something else'}
h[:name] #=> 'Charles'
h["name"] #=> 'Something else'
EDIT:
In your particular situation, it appears request.params["model"]
returns a string instead of a hash. There is a method String#[]
which is a means of getting a substring.
s = "Winter is coming"
s["Winter"] #=> "Winter"
s["Summer"] #=> nil
This would explain your comments.
There are a couple things you can do to remedy your specific situation. I have found the most simplest way to be using JSON
. (I'm sure there are others and maybe those will surface through other answers or through comments.)
require 'json'
hash_of_params = JSON.load(request.params["model"]).to_hash
hash_of_params["password"] #=> "36494092d7d5682666ac04f62d624141"
How to access a symbol hash key using a variable in Ruby
You want to convert your string to a symbol first:
another_family[somevar.to_sym]
If you want to not have to worry about if your hash is symbol or string, simply convert it to symbolized keys
see: How do I convert a Ruby hash so that all of its keys are symbols?
Ruby access hash value by a variable
Old good recursive Ruby 1.9+ solution:
hash = {:test => {:foo => true}}
path = [[:test],[:foo]]
path.flatten.reduce(hash) { |h, p| h[p] }
#⇒ true
Or, as @Stefan suggested in comments:
path.reduce(hash) { |h, (p)| h[p] }
# or even
path.reduce(hash) { |h, p| h[p.first] }
More defensive:
path.flatten.reduce(hash) { |h, p| h.nil? ? nil : h[p] }
Accessing elements of a ruby hash
With a Hash, iteration is made through key first, then value. So have your block use what you need.
test.each do |key|
puts key
end
test.each do |key, value|
puts key
puts value
end
There are also
test.each_key do |key|
puts key
end
test.each_value do |value|
puts value
end
Sidenote: id
is inside test["foo"]
, so maybe you'd need 2 loops
To get id
from your hash directly:
test["foo"]["id"]
test["foo"].each {|k, v| puts "#{k}: #{v}" }
Accessing hash value with variable
Try this:
print "Enter number "
num = gets.chomp().to_i
puts "Value: #{DHASH[num]}"
Accessing hash values with a variable in Ruby is wonderfully easy! You just make sure the variable has the proper key, and then use the variable instead of the key. In your case, the number that you are getting will be a string, and you need it to be an integer, so you need to turn it into an integer. And you need to correct the string interpolation.
Accessing a Ruby hash with a variable as the key
It looks like you want to exec
that last line, as it's obviously a shell command rather than Ruby code. You don't need to interpolate twice; once will do:
exec("rsync -ar root@#{environments['testing']}:/htdocs/")
Or, using the variable:
exec("rsync -ar root@#{environments[current_environment]}:/htdocs/")
Note that the more Ruby way is to use Symbols rather than Strings as the keys:
environments = {
:testing => '11.22.33.44',
:production => '55.66.77.88'
}
current_environment = :testing
exec("rsync -ar root@#{environments[current_environment]}:/htdocs/")
best way to access a hash inside a Ruby module
If you have a method hash_a
that returns @hash_a
then yes, the second form is trivial:
module MyModule
@hash_a = {
key1: "value1",
key2: "value2"
}
def self.hash_a
@hash_a
end
end
Note that Ruby tries to steer away from having get
and set
methods, so if you can express this as something like x
and x=
then it usually works out better. In this case if exposing the Hash directly is acceptable, then just do the simplest thing.
Can't access Hash values
if i am not wrong your hash structure might be like
merchant = {variant_code: 'PRDCT-A'}
variant = {:"PRDCT-A"=>{:price=>1495.0}}
and you want to access variants value with help of merchant hash
you should try this,
variant.dig(merchant[:variant_code].to_sym)
How to access values from a get request in a hash (ruby)
The returned value of get is only a single element hash like {'red' => 3}
If you want to get the key and the value without accessing the entry using
get(var)['red']
=> 3
you could do the following:
get(var).keys.first
=> 'red'
get(var).values.first
=> 3
or you could take the return value and map it into a new hash:
new_hash = {"color" => get(var).keys.first, "id" =>get(var).values.first}
then access like this:
new_hash["color"]
=> red
new_hash["id"]
=> 3
Access Hash with multiple values ruby
A Hash is a collection of key-value pairs like this: "employee" => "salary". It is similar to an Array, except that indexing is done via arbitrary keys of any object type, not an integer index.
The order in which you traverse a hash by either key or value may seem arbitrary and will generally not be in the insertion order. If you attempt to access a hash with a key that does not exist, the method will return nil.
A hash is used to stored large (or small) amounts of data and access it efficiently. For example lets say you have this as a hash:
prices = {
'orange' => 3.15,
'apple' => 2.25,
'pear' => 3.50
}
Now you want to call the keyword apple
and get the prices of those items from some users input:
print 'Enter an item to verify price: '
item = gets.chomp
puts "The price of an #{item}: #{prices[item]}"
# <= The price of an apple: 2.25
That's a basic hash, now lets get into what you're doing, using an Array
as a key.
prices = {
'apple' => ['Granny Smith', 'Red'],
'orange' => ['Good', 'Not good'],
'pear' => ['Big', 'Small']
}
print 'Enter an item for a list: '
item = gets.chomp
puts "We have the following #{item}'s available: #{prices[item]}"
# <= We have the following apple's available: ["Granny Smith", "Red"]
Now if we wanted to grab one of the types:
puts prices[item][0]
# <= Granny Smith
puts prices[item][1]
#<= Red
Now lets get into more advanced techniques like you are doing above, you're idea is great and all, but what you need to do is append the information into the hash
and when you call @name
don't try to call it as a symbol:
h = Hash.new{|hsh,key| hsh[key] = [] }
h[@name] = []
#<= []
h[@name] << ['apple', 'pear']
#<= [["apple", "pear"]]
h[@name] << ['orange', 'apple']
#<= [["apple", "pear"], ["orange", "apple"]]
h[@name].flatten[0]
#<= "apple"
h[@name].flatten[1]
#<= "pear"
h[@name].flatten[1, 2]
#<= ["pear", "orange"]
Alright so what did we do?
h = Hash.new{|hsh,key| hsh[key] = [] }
Created a hash
with a value as an empty array
.
h[@name] = []
Initialized @name
to the empty array
h[@name] << ['apple', 'pear']
Appended an array containing apple, pear
to the @name
key.
h[@name] << ['orange', 'apple']
Appended a second array
containing orange, apple
to the array, so when we call h[@name][1]
right now it will output the first array
appended to it.
h[@name].flatten[0]
Flattened the array
into a single array and called the first element of the array
.
When you call your key (@name
) you don't call it as a symbol, because it's already contained inside of a variable. So all you have to do is call that variable and the value for that key will be output successfully. Hopefully this clarifies a few, things, for more information on hashes
check this out: http://www.tutorialspoint.com/ruby/ruby_hashes.htm
Related Topics
Get Substring After the First = Symbol in Ruby
Rails -- Create and Create! Methods, Ror 3 Tutorial
How to Install Gems with Apt-Get on Ubuntu
How to Debug/Display Request Sent Using Restclient
Ruby 'Each_With_Object' with Index
Configuring Jekyll for Github Project Pages
Ruby: How to Chain Multiple Method Calls Together with "Send"
Installing Ruby 2.0.0 Using Rvm
Regex with Named Capture Groups Getting All Matches in Ruby
Paginate Multiple Models in Kaminari
How Does Rails Implement Before_Filter
What Does the % Operator Do in Ruby in N % 2
Ruby Merging Two Arrays into One
Suitability of Rails, Padrino, and Sinatra for Building a Prepaid Mobile Service
Ruby: Insert Spaces Every X Number of Characters