Accessing instance variable in `each` loop

152 views Asked by At

Is it possible to do something like this?

customer1.shopping_cart.each do |item|
  puts("#{item.name}")

The Item class has an attr_reader for the instance variable name.

1

There are 1 answers

2
Andrew Kozin On
customer1.shopping_cart.each do |item|
  puts("#{item.name}")
end

This will put names for every item from the customer1.shopping_cart collection (presumably array or set)

UPD: A bit more idiomatic syntax:

customer1.shopping_cart.map(&:name).each(&method(:puts))