b.herring
b.herring

Reputation: 643

How to do a simple test in ruby

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

Answers (2)

Hajar
Hajar

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 nils.

Upvotes: 1

Adittya Verma
Adittya Verma

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

Related Questions