I am using Mongoid and retrieving a bunch of BSON::ObjectId instances. Ideally, I'd like to convert them to strings upon retrieval. What's the correct syntax? It can be done in two lines like this:
foo = Bar.where(:some_id => N).map(&:another_id)
ids_as_strings = foo.map(&:to_s)
What's the proper Ruby way to chain to_s after the map invocation above?
This works fine, but don't do it!
ids_as_string = Bar.where(:some_id => N).map(&:another_id).map(&:to_s)
It looks cool for sure, but think about it, you are doing two maps. A map is for looping over an array, or something else, and will operate in each position, retrieving a new array, or something else, with the results.
So why do two loops if you want to do two operations?
ids_as_string = Bar.where(:some_id => N).map {|v| v.another_id.to_s}
This should be the way to go in this situation, and actually looks nicer.
You can just chain it directly:
ids_as_string = Bar.where(:some_id => N).map(&:another_id).map(&:to_s)
I tried this out with a model and I got what you expected, something like:
["1", "2", ...]
Related
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]]}
I saw several variations of this question but did not really find a solid answer.
So I have an array of URLS. I want to loop through that array and for each individual URL, I would create an instance of class WebPages.
So if array URLS has 5 urls in it, then I would create 5 objects of WebPages. I tried to use eval() to do this but quickly learned that the instances made by eval have a very local scope and I cannot use those WebPage objects after.
string_to_eval = #urls.map{|x| "webpage#{urls.index(x)} = WebPage.new('# {x}')"}.join(';')
puts string_to_eval
eval(string_to_eval)
String_to_eval prints out:
webpage0 = WebPage.new('http://www.google.com');
webpage1 = WebPage.new('http://www.yahoo.com');
webpage2 = WebPage.new('http://www.amazon.com');
webpage3 = WebPage.new('http://www.ebay.com')
How else can I make an object with each iteration of the loop in Ruby? Is there a way around this?
Why not just this?
webpages = #urls.map { |url| WebPage.new(url) }
It is generally a bad idea to have webpage0, webpage1... when you can have webpages[0], webpages[1]... (Also, the array way does not require the Evil of eval.)
In this situation I would forgo unique variable names and instead simply leave the resulting objects in an array. In that case the code would look like this:
>> #urls.map{|url| WebPage.new(url)}
=> [WebPage('http://www.google.com'), WebPage('http://www.yahoo.com'), WebPage('http://www.amazon.com'), WebPage('http://www.ebay.com') ]
I am fairly new to Ruby. I have few lines of code I want to DRY them.
foo_attributes = params[:foo]
params.delete(:foo)
bar_attributes = params[:bar]
params.delete(:bar)
I am trying to do something like this
["foo", "bar"].each do |par|
par_attribute = params[:par]
params.delete(:par)
end
Later in my method, I need to call other methods passing the objects foo_attribute, bar_attribute.
Like:
call_foo_method(foo_attribute)
How can I do this in ruby?
Why don't you just keep the params var? Then you don't have to assign any other variable at all?
You can also DRY the first (and second example) by combinig two lines:
foo_attributes = params.delete(:foo)
bar_attributes = params.delete(:bar)
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"] }
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)