1

I have this block of code:

super_heroes = [ ["Spider Man", "Peter Parker"], ["Deadpool", "Wade Wilson"], ["Wolverine", "James Howlett"] ] super_heroes.each do |sh| sh.each do |heroname, realname| puts "#{realname} is #{heroname}" end end 

The output is this:

 is Spider Man is Peter Parker is Deadpool is Wade Wilson is Wolverine is James Howlett 

But I wanted to be this:

Peter Parker is Spider Man Deadpool is Wade Wilson Wolverine is James Howlett 

After hours of iterating the code, I still couldn't figure it out. I would appreciate if someone could put me in the right direction and explain what I'm doing wrong. Thanks!

0

2 Answers 2

4

Do as below :

super_heroes = [ ["Spider Man", "Peter Parker"], ["Deadpool", "Wade Wilson"], ["Wolverine", "James Howlett"] ] super_heroes.each do |heroname, realname| puts "#{realname} is #{heroname}" end # >> Peter Parker is Spider Man # >> Wade Wilson is Deadpool # >> James Howlett is Wolverine 

What happened with your code ?

super_heroes.each do |sh| # sh is ["Spider Man", "Peter Parker"] etc.. # here **heroname** is "Spider Man", "Peter Parker" etc. # every ietration with sh.each { .. } your another variable **realname** # is **nil** sh.each do |heroname, realname| puts "#{realname} is #{heroname}" # as **realname** is always **nil**, you got the output as # is Spider Man # is Peter Parker # ..... # ..... end end 
Sign up to request clarification or add additional context in comments.

1 Comment

That works! Why didn't I think of that!!! Knowing that it's a 2D array my extinct told me to maybe use .each method twice. @mdsantis: "Flash" badge indeed.
1

Try this also,

super_heroes.each do |sh| puts sh.join(" is ") end 

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.