The & thing can be handy, used sparingly, and the Rails issue of pulling results into memory to process them, rather than using 'pluck' etc is a real thing, but I agree the other suggestions are garbage.
I think this blog is called 'Ruby Magic', and Rails especially has that reputation of being inscrutable magic; these suggestions just make it worse. Forget idioms and using obscure features of the language or framework - just write simple clear code.
I’ve written a lot of ruby code but am not super advanced. Can you elaborate on what you mean about “pluck” and memory? Came across it in rails docs yesterday but haven’t seen it used in a codebase before
My guess is that they're referring to how Rails will instantiate full objects for ActiveRecord database requests and this is often not what you want, because we often just want a single or a few attributes from the model.
So if you had a model Activity, and you wanted to get the names of some of them, the slower/higher memory approach would be something like:
Activity.where("id < 100").map(&:name)
This pulls results from the database, instantiates each as Activity objects, then iterates through each to get its name. You can see in the logs that it grabs the entire object:
Activity Load (133.7ms) SELECT "activities".* FROM "activities" WHERE (id < 100)
.pluck instead grabs just the field you're looking for without instantiating the entire object. So the better way to grab the list of activity names would be like:
Activity.where("id < 100").pluck(:name)
And you can see from the logs that it makes a more narrow query:
(3.8ms) SELECT "activities"."name" FROM "activities" WHERE (id < 100)
Awesome thanks for the reply, am making an effort to learn more activerecord and didn’t know pluck would function like this. Was playing around with it last night on a ruby hash and missed the memory advantages
I think this blog is called 'Ruby Magic', and Rails especially has that reputation of being inscrutable magic; these suggestions just make it worse. Forget idioms and using obscure features of the language or framework - just write simple clear code.