18/19 I'm Blocked by Blocks


#1

I can't seem to get my code to work. This is what I have so far---

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

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

puts my_array

--- And it wont even square the values in the array.


#2

You're getting close!

Try placing the puts within your my_array.each, not outside of it. Your puts my_array will only put out the numbers [1,2,3,4,5] which are in that array.

Your my_array.each {.....} is working in the background, but not being put out.


#3

Thanks. I eventually made it past by changing my code to

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

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

I can't figure out how to use the curly braces efficiently but at least I can get through it at all :3


#4

Congrats on making it past! That's nearly the same code as what @cmditch suggested. Though, technically, you should write your code as:

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

my_array.each do |n|
  product = n * n # sum would be n + n
  puts product 
end

to make it accurately descriptive.

P.S. Here's a tutorial on how to format code.

Hope it helps!


#5

Thanks, this Helped me a lot.


#6

I've tryed
my_array.each {|x| puts " #{x * x} "}
and it perfectly works, but I can't pass the course with this line. why is that?


#7
my_array.each {|x| pr = x * x 
    puts " #{pr} "}

doesn't work eather. The #{} were was not accepted here even though it works.


#8

Hi 0body, I agree this is a bit confusing and strange error. The reason why the exercise gives this error is that it expects each number to be completely on a line on its own. Right now your numbers are accompanied by two spaces (one each on right and left). Removing them:

my_array.each {|x| pr = x * x 
    puts "#{pr}"}

works fine :slight_smile:


#13

This worked for me:

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

my_array.each do |my_array|
sum = my_array**2
puts sum
end


#14

works)

my_array = [1, 2, 3, 4, 5]
sum = []
my_array.each {|n| sum << n * n}
puts sum


#15

try this:

my_array.each { |x| puts x * x }

By using puts, you're already telling Ruby to print out the results to the screen.

Since the instructions ask us to iterate over each number in the array and multiply it by itself, you're already accomplishing this by placing x * x in your block.


#16

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

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


#17