Reputation: 643
I have some code below that gives square numbers. I also wrote a simple test that prints true
or false
.
numbers = (1..20)
test=numbers.each do |number|
puts number * number
end
puts test == [1,4,9,16,25,36,49,64,81,100,121,144,169,196,225,256,289,324,361,400]
I expect it to print true
, but it puts false
.
I was wondering if anyone could help to see why.
Upvotes: 0
Views: 55
Reputation: 157
In your code numbers.each do |number| .. end
returns the range (1..20) and that's the value that test will be assigned to after the loop through numbers
is done. So even if you deleted the line puts number* number
, test will still have the value (1..20). So using map
would be the right choice to keep your values in an array. But you should first delete puts
, because it shows the value on the screen but returns nil
. So if you used map
but didn't delete puts
test will be assigned to an array of nil
s.
Upvotes: 1
Reputation: 289
Try below code to get your answer :
numbers = (1..20)
test = numbers.map{|a| a*a}
puts test == [1,4,9,16,25,36,49,64,81,100,121,144,169,196,225,256,289,324,361,400]
You are using first test which contents 1..20
. So you have to modify your code.
Upvotes: 1