My form receives data via POST. When I do puts params I can see:
{"id" => "123", "id2" => "456"}
now the commands:
puts params['id'] # => 123
puts params[:id] # => 123
params['id'] = '999'
puts params # => {"id" => "999", "id2" => "456"}
but when I do:
params[:id] = '888'
puts params
I get
{"id" => "999", "id2" => "456", :id => "888"}
In IRB it works fine:
params
# => {"id2"=>"2", "id"=>"1"}
params[:id]
# => nil
params['id']
# => "1"
Why can I read the value using :id, but not set the value using that?
Hashes in Ruby allow arbitrary objects to be used as keys. As strings (e.g. "id") and symbols (e.g. :id) are separate types of objects, a hash may have as a key both a string and symbol with the same visual contents without conflict:
irb(main):001:0> { :a=>1, "a"=>2 }
#=> {:a=>1, "a"=>2}
This is distinctly different from JavaScript, where the keys for objects are always strings.
Because web parameters (whether via GET or POST) are always strings, Sinatra has a 'convenience' that allows you to ask for a parameter using a symbol and it will convert it to a string before looking for the associated value. It does this by using a custom default_proc that calls to_s when looking for a value that does not exist.
Here's the current implementation:
def indifferent_hash
Hash.new {|hash,key| hash[key.to_s] if Symbol === key }
end
However, it does not provide a custom implementation for the []=(key, val) method, and thus you can set a symbol instead of the string.
Related
A hash (with key of class String) can be defined using hash rocket syntax like so:
h = {:name => 'Charles', "name" => 'John'}
Is there a way to define it using another notation?
I tried:
a = {name: "Charles", "name": "John"}
(irb):14: warning: key :name is duplicated and overwritten on line 14
a
# => {:name=>"John"}
Also note that without any overriding, I still can't spot a way to get the key to be class String:
b = {"name": "John"}
b
# => {:name=>"John"} # "name" (String) is stored as :name (Symbol)
AFAIK it's not possible to define a hash with any String keys using the more modern hash notation (the notation that doesn't use the hash rockets). Is there any way, or should the => has rockets be used when defining a hash with a key of class String?
The documentation really makes this pretty clear:
The older syntax for Hash data uses the “hash rocket,” =>:
h = {:foo => 0, :bar => 1, :baz => 2} h # => {:foo=>0, :bar=>1,
> :baz=>2}
Alternatively, but only for a Hash key that's a Symbol, you can use a
newer JSON-style syntax...
I have an array of hashes to write a generic checker for, so I want to pass in the name of a key to be checked. The hash was defined with keys with symbols (colon prefixes). I can't figure out how to use the variable as a key properly. Even though the key exists in the hash, using the variable to access it results in nil.
In IRB I do this:
>> family = { 'husband' => "Homer", 'wife' => "Marge" }
=> {"husband"=>"Homer", "wife"=>"Marge"}
>> somevar = "husband"
=> "husband"
>> family[somevar]
=> "Homer"
>> another_family = { :husband => "Fred", :wife => "Wilma" }
=> {:husband=>"Fred", :wife=>"Wilma"}
>> another_family[somevar]
=> nil
>>
How do I access the hash key through a variable? Perhaps another way to ask is, how do I coerce the variable to a symbol?
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?
You can use the Active Support gem to get access to the with_indifferent_access method:
require 'active_support/core_ext/hash/indifferent_access'
> hash = { somekey: 'somevalue' }.with_indifferent_access
=> {"somekey"=>"somevalue"}
> hash[:somekey]
=> "somevalue"
> hash['somekey']
=> "somevalue"
Since your keys are symbols, use symbols as keys.
> hash = { :husband => 'Homer', :wife => 'Marge' }
=> {:husband=>"Homer", :wife=>"Marge"}
> key_variable = :husband
=> :husband
> hash[key_variable]
=> "Homer"
If you use Rails with ActiveSupport, then do use HashWithIndifferentAccess for flexibility in accessing hash with either string or symbol.
family = HashWithIndifferentAccess.new({
'husband' => "Homer",
'wife' => "Marge"
})
somevar = "husband"
puts family[somevar]
#Homer
somevar = :husband
puts family[somevar]
#Homer
The things that you see as a variable-key in the hash are called Symbol is a structure in Ruby. They're primarily used either as hash keys or for referencing method names. They're immutable, and Only one copy of any symbol exists at a given time, so they save memory.
You can convert a string or symbol with .to_sym or a symbol to string with .to_s to illustrate this let me show this example:
strings = ["HTML", "CSS", "JavaScript", "Python", "Ruby"]
symbolArray = [:HTML, :CSS, :JavaScript, :Python, :Ruby]
# Add your code below!
symbols = Array.new
strings.each {|x|
symbols.push(x.to_sym)
}
string = Array.new
symbolArray .each {|x|
string.push(x.to_s)
}
print symbols
print string
the result would be:
[:HTML, :CSS, :JavaScript, :Python, :Ruby]
["HTML", "CSS", "JavaScript", "Python", "Ruby"]
In ruby 9.1 you would see the symbols with the colons (:) in the right instead:
movies = { peter_pan: "magic dust", need_4_speed: "hey bro", back_to_the_future: "hey Doc!" }
I just wanted to make this point a litter more didactic so who ever is reading this can used.
One last thing, this is another way to solve your problem:
movie_ratings = {
:memento => 3,
:primer => 3.5,
:the_matrix => 3,
}
# Add your code below!
movie_ratings.each_key {|k|
puts k.to_s
}
result:
memento
primer
the_matrix
I want to define a method_missing function for one of my classes, and I want to be able to pass in a hash as the argument list instead of an array. Like this:
MyClass::get_by_id {:id => id}
MyClass::get_by_id {:id => id, :filters => filters}
MyClass::get_by_id {:id => id, :filters => filters, :sort => sort}
As far as I can tell, the args list gets passed in as an array, so keys get dropped and there's no way to tell which arguments is which. Is there a way to force Ruby to treat the argument list in method_missing as a hash?
What issue are you having? This works for me:
class MyClass
def self.method_missing name, args
puts args.class
puts args.inspect
end
end
MyClass.foobar :id => 5, :filter => "bar"
# Hash
# {:id=>5, :filter=>"bar"}
Is this what you are looking for ?
class Foo
def self.method_missing(name,*args)
p args
p name
end
end
Foo.bar(1,2,3)
# >> [1, 2, 3]
# >> :bar
I'm answering my own question based on experimentation that I've done since asking. When using a hash splat on the arg list, you can pass in a hash like this:
MyClass::get_by_id(:id => id, :filters => filters)
And the argument list will look like this:
[
{
:id => id,
:filters => filters
}
]
Ruby places the key/value pairs into a single hash object at location args[0]. If you call the method like this:
MyClass::get_by_id(id, :filters => filters)
Your argument list will be this:
[
id,
{:filters => filters}
]
So basically, key/value pairs are merged together into a single hash and passed in order.
I would like to return the results of a SOQL query as JSON, but the data seems to be returned as a string.
client = SFDC_Adapter.login
data = client.query("SELECT MarkupAmount__c,
MarkupPercent__c,
Product_Type_Id__c,
Product_Type__c
FROM Product_Type__c
WHERE Product_Type_Id__c = #{product_type_id}")
p data
=> [#<Product_Type__c:0x00000001c356f8 #Id=nil, #OwnerId=nil, #IsDeleted=nil, #Name=nil, #CreatedDate=nil, #CreatedById=nil, #LastModifiedDate=nil, #LastModifiedById=nil, #SystemModstamp=nil, #MarkupPercent__c=5.0, #Subscription__c=nil, #Product_Type__c="Research Trip", #MarkupAmount__c=nil, #Product_Type_Id__c=36.0>]
puts data
=> #<Product_Type__c:0x00000001c356f8>
puts data.to_json
=> ["#<Product_Type__c:0x00000001c356f8>"]
How do I materialize these results into a JSON object for use in a Restful service?
I don't know that gem, but from looking at your output, and glancing at your results, it looks like you got a Product_Type object back.
When you use p or puts, inspect is being used, which is turning the instance into something viewable in a web-page, by using an HTML encoding on it. That's why you see < and > in the output.
Instead, you need to access the values in the object. According to the docs, you can use standard getters or using a hash[key] form to do that:
contact = Contact.find("contact_id") #=> #
contact = Contact.find_by_Name("John Smith") #=> dynamic finders!
contacts = Contact.all #=> a Databasedotcom::Collection of Contact instances
contacts = Contact.find_all_by_Company("IBM") #=> a Databasedotcom::Collection of matching Contacts
contact.Name #=> the contact's Name attribute
contact["Name"] #=> same thing
contact.Name = "new name" #=> change the contact's Name attribute, in memory
contact["Name"] = "new name" #=> same thing
contact.save #=> save the changes to the database
contact.update_attributes "Name" => "newer name",
"Phone" => "4156543210" #=> change several attributes at once and save them
contact.delete #=> delete the contact from the database
Try data['Product_Type_Id'] and you should get 36.0. An alternate way of doing the same thing is data.Product_Type_Id.
Once you have your accessors figured out you can generate JSON using a simple hash or array of hashes. This would generate a hash:
require 'json'
hash = {
'Id' => data.Id,
'OwnerId' => data.OwnerId,
'IsDeleted' => data.IsDeleted,
'Name' => data.Name,
'CreatedDate' => data.CreatedDate,
'CreatedById' => data.CreatedById,
'LastModifiedDate' => data.LastModifiedDate,
'LastModifiedById' => data.LastModifiedById,
'SystemModstamp' => data.SystemModstamp,
'MarkupPercent' => data.MarkupPercent,
'Subscription' => data.Subscription,
'Product_Type' => data.Product_Type,
'MarkupAmount' => data.MarkupAmount,
'Product_Type_Id' => data.Product_Type_Id,
}
puts hash.to_json
I didn't see a to_h or to_hash method which would be a shortcut.
I have an array of hashes
Eg:
cars = [{:company => "Ford", :type => "SUV"},
{:company => "Honda", :type => "Sedan"},
{:company => "Toyota", :type => "Sedan"}]
# i want to fetch all the companies of the cars
cars.collect{|c| c[:company]}
# => ["Ford", "Honda", "Toyota"]
# i'm lazy and i want to do something like this
cars.collect(&:company)
# => undefined method `company'
I was wondering if there is a similar shortcut to perform the above.
I believe your current code cars.collect{|c| c[:company]} is the best way if you're enumerating over an arbitrary array. The method you would pass in via the & shortcut would have to be a method defined on Hash since each object in the array is of type Hash. Since there is no company method defined for Hash you get the "undefined method 'company'" error.
You could use cars.collect(&:company) if you were operating on an Array of Cars though, because each object passed into the collect block would be of type Car (which has the company method available). So maybe you could modify your code so that you use an array of Cars instead.
You could convert the hashes to OpenStructs.
require 'ostruct'
cars = [{:company => "Ford", :type => "SUV"},
{:company => "Honda", :type => "Sedan"},
{:company => "Toyota", :type => "Sedan"}]
cars = cars.map{|car| OpenStruct.new(car)}
p cars.map( &:company )
#=> ["Ford", "Honda", "Toyota"]
It's impossible to use in your case, because in collect you use method [] and argument :company. The construction &:company takes labels :company and converts to Proc, so it's only one argument - the name of method.
Unfortunately Ruby hashes can't do that. Clojure maps on the other hand have functions for each key which return the corresponding value, which would be easy enough to do if you are so inclined (you should also add the corresponding respond_to? method):
>> class Hash
.. def method_missing(m)
.. self.has_key?(m) ? self[m] : super
.. end
.. end #=> nil
>> cars.collect(&:company) #=> ["Ford", "Honda", "Toyota"]
>> cars.collect(&:compay)
NoMethodError: undefined method `compay' for {:type=>"SUV", :company=>"Ford"}:Hash
Note: I'm not advising this, I'm just saying it's possible.
Another horrible monkeypatch you shouldn't really use:
class Symbol
def to_proc
if self.to_s =~ /bracket_(.*)/
Proc.new {|x| x[$1.to_sym]}
else
Proc.new {|x| x.send(self)}
end
end
end
cars = [{:company => "Ford", :type => "SUV"},
{:company => "Honda", :type => "Sedan"},
{:company => "Toyota", :type => "Sedan"}]
cars.collect(&:bracket_company)