Reputation: 1665
I have an instance people = Person.all
and would like to loop over it to get the first_name attribute for each person. I have tried the following:
people.each do |first_name|
puts #{first_name}
end
How to construct the loop as to output all of the First Names?
Upvotes: 0
Views: 203
Reputation: 710
What if, instead of looping, we fetch all the first names in one query?
puts Person.pluck(:first_name).join("\n")
If it needs to be an array of people, this would work too
puts people.map(&:first_name).join("\n")
Upvotes: 0
Reputation: 4053
Redo your code so it looks like this:
people.each do |person|
puts person.first_name
end
In this code, person
is the name of the individual object you are looping over. So calling person.first_name
will call the first_name of that individual.
Upvotes: 2