Reputation: 103
I want to understand:
I have this code:
produto = ActiveRecord::Base.connection.exec_query("SELECT * FROM produtos")
Return of produtos
#<ActiveRecord::Result:0xb774bc8 @columns=["id", "nome"], @rows=[[1, "yuri"], [2, "Igor"], [3, "Iran"], [4, "Hotaviano"], [5, "Maria"], [6, "José"], [7, "Mateus"], [8, "kaun"]], @hash_rows=nil, @column_types={}>
When I do this:
produto.map { |p| Produto.new(p) }
It returns the following:
[
#<Produto:0xad8fd60 @id=1, @nome="yuri">,
#<Produto:0xad8fbe4 @id=2, @nome="Igor">,
#<Produto:0xad8fbd0 @id=3, @nome="Iran">,
#<Produto:0xad8fb1c @id=4, @nome="Hotaviano">,
#<Produto:0xad8facc @id=5, @nome="Maria">,
#<Produto:0xad8f9b4 @id=6, @nome="José">,
#<Produto:0xad8f9a0 @id=7, @nome="Mateus">,
#<Produto:0xad8f784 @id=8, @nome="kaun">
]
Upvotes: 1
Views: 957
Reputation: 20263
Apologies for being nit-picky, but map
is not a function. It is a method. And, according to the docs, it
creates a new array containing the values returned by the block.
So, to your first question, the map method returns an array of produti
because an instance of Produto
is the value returned by the block.
To your second question, the map
method, using @columns
, is creating a hash
(p
) like:
{id: 1, nome: 'yuri'}
For each entry in @rows
which is then used to instantiate each instance of Produto
when you do Produto.new(p)
.
Try:
produto.map do |p|
puts p
Produto.new(p)
end
to check it out.
Upvotes: 3