Converting multiple arrays into a single hash - ruby

I'm working on a configuration file parser and I need help parsing key: value pairs into a hash.
I have data in the form of: key: value key2: value2 another_key: another_value.
So far I have code in form of
line = line.strip!.split(':\s+')
which returns an array in the form of
["key:value"]["key2: value2"]["another_key: another_value"]
How can I turn these arrays into a single hash in the form of
{key=>value, key2=>value2, another_key=>another_value}
I'm not sure if the key:value pairs need to be in the form of a string or not. Whatever is easiest to work with.
Thanks for your help!
This is the solution I found:
line = line.strip.split(':')
hash = Hash[*line]
which results in the output{"key"=>"value"}, {"key2"=>"value2"}

Very very close to Cary's solution:
Hash[*line.delete(':').split]

Even simpler:
Hash[*line.gsub(':',' ').split]
# => {"key"=>"value", "key2"=>"value2", "another_key"=>"another_value"}

Assuming the key and value are single words, I'd probably do something like this:
Hash[line.scan(/(\w+):\s?(\w+)/)]
You can change the regex if it's not quite what you are looking for.

Related

Ruby Array sort_by value in variable

I would like to sort Ruby Array by key in variable, but I don't know how.
Situation
my_arr.sort_by {|record| [record.year]}
Will sort by a year of the record. But I want to sort by author, label, etc. And this sort type is stored in a variable like a String. So I need to evaluate the filter like
my_arr.sort_by {|record| [record."something_in_the_var"]}
Of course, I have fixed filters. But still figuring out how to do it properly.
Thanks for tips
This is what send does
str = "label"
arr.sort_by{|rec| rec.send(str) }
send is defined on BasicObject, so every object has it.
you can use something like
sort_by_this = "label"
my_arr.sort_by {|record| [record[sort_by_this]]}

Compare Json Response to Json text File

I have a file text.json and I have an JSON HTTP response. What's a good to check if they are equal?
Here's what I have but I think there's a better solutions.
JSON.parse(response["data"]).eql?(File.read(text.json))
You need to parse both ends of your test:
JSON.parse(response["data"]).eql?(JSON.parse(File.read(text.json)))
Edit
If you want to test an array of JSONs, and you are not sure that the order will be the same in the file meaning [{a:1, b:2}, {a:2, b:1}] should equal [{a:2, b:1}, {a:1, b:2}], you'll need to sort them first (see here for more techniques):
JSON.parse(response["data"]).sort.eql?(JSON.parse(File.read(text.json)).sort)
Edit 2
Since Hashes don't sort well, the above won't work. You could use one of the other techniques:
from_response = JSON.parse(response["data"])
from_file = JSON.parse(File.read(text.json))
(from_response & from_file) == from_response
(from_response - from_file).empty?

how to find a hash key with one of the predefined names?

I have a hash with an arbitrary key:
{'GET': [1,2,3]}
or
{'POST': ['my data 0', 'my data 1']}
The hash is generated from JSON which is sent in the request body. There is just one key, or rather, I ignore any keys but one.
I want to find which key it is, and this is the code that I wrote:
items = data['GET'] || data['get'] || data['POST'] || data['post']
this does not look neat. If the number of keys that I want to process grows the expression will be long. I want it to be short. I am new to Ruby, is there a better way?
If you think it might grow, you may want to separate the HTTP methods from the finding of that method in the data:
methods = [:get, :post]
def find_method(data)
keys = methods.map{|m| [m.to_s.upcase, m.to_s]}.flatten
data.values_at(keys).first
end
You could just get the first value (assuming there's only one) like this:
item = data.values.first
You could use the Hash#values_at method.
http://www.ruby-doc.org/core-1.9.3/Hash.html#method-i-values_at
data.values_at('GET','get', 'POST','post').first

How do I extract a value from this Ruby hash?

I'm using the Foursquare API, and I want to extract the "id" value from this hash
[{"id"=>"4fe89779e4b09fd3748d3c5a", "name"=>"Hitcrowd", "contact"=>{"phone"=>"8662012805", "formattedPhone"=>"(866) 201-2805", "twitter"=>"hitcrowd"}, "location"=>{"address"=>"1275 Glenlivet Drive", "crossStreet"=>"Route 100", "lat"=>40.59089895083072, "lng"=>-75.6291255071468, "postalCode"=>"18106", "city"=>"Allentown", "state"=>"Pa", "country"=>"United States", "cc"=>"US"}, "categories"=>[{"id"=>"4bf58dd8d48988d125941735", "name"=>"Tech Startup", "pluralName"=>"Tech Startups", "shortName"=>"Tech Startup", "icon"=>"https://foursquare.com/img/categories/shops/technology.png", "parents"=>["Professional & Other Places", "Offices"], "primary"=>true}], "verified"=>true, "stats"=>{"checkinsCount"=>86, "usersCount"=>4, "tipCount"=>0}, "url"=>"http://www.hitcrowd.com", "likes"=>{"count"=>0, "groups"=>[]}, "beenHere"=>{"count"=>0}, "storeId"=>""}]
When I try to extract it by using ['id'], I get this error can't convert Symbol into Integer. How do I extract the value using ruby? Also, how do I do this for multiple hashes extracting the "id" value each time?
Please pardon my inexperience. Thanks!
It's wrapped in an array, that's what the [ and ] mean on the start and end. But it also looks like this array only one object in it, which is the hash you really want.
So assuming you want the first object in this array:
mydata[0]['id'] # or mydata.first['id'] as Factor Mystic suggests
But usually when an API returns an Array there is a reason (it might return many results instead of just one), and naively plucking the first item from it my not be what you want. So be sure you are getting the kind of data you really expect before hard coding this into your application.
For multiple hashes, if you want to do something with the id (run a procedure of some kind) then
resultsArray.each do |person|
id = person["id"] #then do something with the id
end
If you want to just get an array containing the ids then
resultsArray.map{|person| person["id"]}
# ["4fe89779e4b09fd3748d3c5a", "5df890079e4b09fd3748d3c5a"]
To just grab the one item from the array, see Alex Wayne's answer
To get an array of ids, try: resultsArray.map { |result| result["id"] }

Ruby: How can I make these objects the same?

So I have the following hashes/arrays:
{"number"=>[{"tracking"=>"1Z81E74W0393736553", "notes"=>"Example note"}, {"tracking"=>"9102901001301227214058"}]}
{"number"=>{"tracking"=>"1Z81E74W0393736553", "notes"=>"Example note"}}
That first hash has an array for number while the second one doesn't.
It's wreaking havoc trying to loop through the data (specifically when there's only one tracking/notes combo).
Ultimately I'm wanting to be able to do an each loop on each tracking/notes combo.
h1={"number"=>[{"tracking"=>"1Z81E74W0393736553", "notes"=>"Example note"}, {"tracking"=>"9102901001301227214058"}]}
h2={"number"=>{"tracking"=>"1Z81E74W0393736553", "notes"=>"Example note"}}
[h1["number"]].flatten
=> [{"notes"=>"Example note", "tracking"=>"1Z81E74W0393736553"}, {"tracking"=>"9102901001301227214058"}]
[h2["number"]].flatten
=> [{"notes"=>"Example note", "tracking"=>"1Z81E74W0393736553"}]
Now, each will be an array of hashes and you can use each to iterate through them.
Something like this?
hash["number"] = [ hash["number"] ] unless hash["number"].kind_of?(Array)

Resources