If I type in my console
u = User.first u.friends(&map:username)
I get ["Peter", "Mary", "Jane"]
but I also want to show the birthday, so how do I do that? I tried
u.friends(&map:username, &map:birthday)
but this doesn't work.
The difference between map and each is given as following: Array#each executes the given block for each element of the array, then returns the array itself. Array#map also executes the given block for each element of the array, but returns a new array whose values are the return values of each iteration of the block.
The way the map method works in Ruby is, it takes an enumerable object, (i.e. the object you call it on), and a block. Then, for each of the elements in the enumerable, it executes the block, passing it the current element as an argument. The result of evaluating the block is then used to construct the resulting array.
1 What is Active Record? Active Record is the M in MVC - the model - which is the layer of the system responsible for representing business data and logic. Active Record facilitates the creation and use of business objects whose data requires persistent storage to a database.
Map is a Ruby method that you can use with Arrays, Hashes & Ranges. The main use for map is to TRANSFORM data. For example: Given an array of strings, you could go over every string & make every character UPPERCASE.
You can use the alternate block syntax:
u.friends.map{|f| [f.username, f.birthday]}
which would give an array of arrays.
u.friends.map{|f| "#{f.username} - #{f.birthday}"}
would give you an array of strings. You can do quite a bit from there.
With ActiveRecord >= 4 you can simply use:
u.friends.pluck(:username, :birthday)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With