Methods, Blocks & Sorting - 18 - Can someone explain the logic?


Hey guys, so I'm getting ready for a Maker's interview. This is my first run through the Ruby course on Codecademy. As usual there's the 'logic' leap on a few of the sections - just when I think I'm getting the hang of it - there's a question to make me feel dumb again!

I've googled/the current help on 18/Methods/Blocks&Sorting and only one line of code in the help let's me pass. I'm trying to get that stage beyond simply copying a block that works and moving on (gratefully) so that I can actually understand the logic of each stage. If someone could walk me through the below that would be appreciated. The block that works is this:

my_array = [1, 2, 3, 4, 5]

my_array.each {|n| puts n**=2}

The basic idea I get is that we're trying iterate through each element in the Array and print it out squared i.e. 1*1, 2*2 etc. what I don't get is the structure of the above "n**=2" as an answer - How does this work based on what has gone before? Shouldn't n*n work?

I originally was trying the 'do' method way so something like:

my_array = [1, 2, 3, 4, 5]

my_array.each do |n|
n = n*n
puts my_array

Could anyone walk me through this?



You say "work", but what do you mean? That's a word used for avoiding to consider and explain what you want. What should it do, and why would your code have that effect? Just considering what should be done here is a big clue for what you need to change. Consider what effect your code has and what effect it should have. What is the difference in behaviour? What does it need to do differently?


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.