Printing out contents of 2 arrays using a loop

Hi. I’d like to print out the contents of 2 arrays as follows…

print array1[0] array2[0]
print array1[1] array2[1]
etc

array1 holds names
array2 holds occupation

so an example print out will be…

Joe Bloggs Carpenter
etc

I’m struggling constructing a loop or iteration that prints this out.
The psuedocode is something as follows…

for length of array1
print out contents of array1 and array2

or something similar

Any help is appreciated thanks.

On Tue, Nov 2, 2010 at 5:19 PM, Paul R. [email protected]
wrote:

or something similar

Any help is appreciated thanks.

irb(main):001:0> a1 = [“joe blogs”, “peter smith”]
=> [“joe blogs”, “peter smith”]
irb(main):002:0> a2 = [“carpenter”, “policeman”]
=> [“carpenter”, “policeman”]
irb(main):003:0> a1.zip(a2).each {|name, occupation| puts “#{name} is
a #{occupation}”}
joe blogs is a carpenter
peter smith is a policeman

Another way that avoids creating the intermediate array would be to
iterate using the index:

irb(main):004:0> a1.each_with_index {|name, i| puts “#{name} is a
#{a2[i]}”}
joe blogs is a carpenter
peter smith is a policeman
=> [“joe blogs”, “peter smith”]

Jesus.

Great. Thanks a million

On Tue, Nov 2, 2010 at 12:19 PM, Paul R. [email protected]
wrote:

Joe Bloggs Carpenter
etc

I’m struggling constructing a loop or iteration that prints this out.

names = %w(joe sam john fred)
occupations = %w(tinker tailor soldier spy)

names.zip(occupations).each {|name, occupation| puts “#{name} is a
#{occupation}”}


Rick DeNatale

Help fund my talk at Ruby Conf 2010:http://pledgie.com/campaigns/13677
Blog: http://talklikeaduck.denhaven2.com/
Github: rubyredrick (Rick DeNatale) · GitHub
Twitter: @RickDeNatale
WWR: http://www.workingwithrails.com/person/9021-rick-denatale
LinkedIn: http://www.linkedin.com/in/rickdenatale

On 02.11.2010 17:36, Rick DeNatale wrote:

so an example print out will be…

names.zip(occupations).each {|name, occupation| puts “#{name} is a
#{occupation}”}

#zip accepts a block, which avoids creating the merged Array:

irb(main):005:0> names.zip(occupations){|name, occupation| puts “#{name}
is a #{occupation}”}
joe is a tinker
sam is a tailor
john is a soldier
fred is a spy
=> nil

Kind regards

robert