Accessing variables of instances in an array?

P

Paul Roche

Hi. I want to have an array of instances.......

listb = [instance1, instance2, instance3]

I am able to print out the instance.....

def printout(an_array)
an_array.each {|item| p item }
end
printout(listb)


How can I print out specific variables for each instance?


eg variables...

name
age
 
J

Jeremy Bopp

Hi. I want to have an array of instances.......

listb = [instance1, instance2, instance3]

I am able to print out the instance.....

def printout(an_array)
an_array.each {|item| p item }
end
printout(listb)


How can I print out specific variables for each instance?


eg variables...

name
age

an_arry.each { |item| puts "#{item.name} #{item.age}" }

-Jeremy
 
J

Jeremy Bopp

Thanks Jeremy, that does the job. By the way is 'item' a keyword?

No, item is not a keyword. You can replace that with any valid variable
name. When you start using other methods that take blocks, you'll find
that you can use more than one variable within the | ... | as well.
Some blocks even take an empty list.

-Jeremy
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,145
Messages
2,570,825
Members
47,371
Latest member
Brkaa

Latest Threads

Top