0
class Person attr_reader = :name, :location def initialize(name, location) @name = name @location = location end end persons_array = [Person.new("Shon", "Texas"), Person.new("Michael", "California"), Person.new("Chris, "california") ] 

I am trying to iterate through the array above and display "Shon is in Texas." I tried persons_array.each { puts "#{@name} is in "#{location}", but no luck.

2
  • 1
    Thanking everyone for submitting an answer is discourage on SO, for good reasons. Firstly, it's a waste of time for readers. Socondly, you don't want to encourage poor answers. Thirdly, if someone submits a killer answer and you say "Great answer!!", what are they to think? And lastly, if you forget to thank someone for their answer, readers may conclude you evidently don't like that one. Don't fell bad, many newcomers do this. Read this when you have time. Commented Nov 21, 2014 at 20:11
  • If you didn't have the read accessors, you could write: [Person.new("Luke", "big trouble")].map { |obj| "#{obj.instance_variable_get(:@name)} is in #{obj.instance_variable_get(:@location)}" } => ["Luke is in big trouble"]. Commented Nov 21, 2014 at 20:24

2 Answers 2

1

Three issues with your code:

  • the attr_reader line should not have the equals sign
  • on the last line, in the block passed to each you have to declare the person variable between pipe signs (|)
  • inside the each block you have to call the name and location accessors for the person instance, you don't have access to the local variables (ex: @name).

Here's the full code:

class Person attr_reader :name, :location def initialize(name, location) @name = name @location = location end end persons_array = [ Person.new("Shon", "Texas"), Person.new("Michael", "California"), Person.new("Chris", "california") ] persons_array.each{ |p| puts "#{p.name} is in #{p.location}" } 

And here's how it works: http://ideone.com/rMgpPd

Sign up to request clarification or add additional context in comments.

Comments

1

You have some syntax errors.

It should be attr_reader :name and not attr_reader = :name. In fact, attr_reader is a method that takes in any number of arguments, and you can call it like so: attr_reader(:name, :location) which will still work.

You can take a look at how |variable| works in a Ruby block here: What are those pipe symbols for in Ruby?

class Person attr_reader :name, :location def initialize(name, location) @name = name @location = location end end persons_array = [Person.new("Shon", "Texas"), Person.new("Michael", "California")] persons_array.each do |person| puts "#{person.name} is in #{person.location}" end 

will print

Shon is in Texas Michael is in California 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.