Question on do block

C

CompGeek78

While going through some practice code from a book, I ran into an odd
issue with this do block.

The book put the code this way and it worked fine.

def mtdarry
10.times do |num|
square = num * num
return num, square if num > 7
end
end

num, square = mtdarry
puts num
puts square

This returns 8 and 64, which makes sense.

The problem I ran into is in changing the > to a =.

def mtdarry
10.times do |num|
square = num * num
return num, square if num = 7
end
end

num, square = mtdarry
puts num
puts square

At this point, it outputs 7 and 0. Why does it not calculate the value
of square properly?
 
G

Gregory Brown

The problem I ran into is in changing the > to a =.

def mtdarry
10.times do |num|
square = num * num
return num, square if num = 7
end
end

You want an equality check, not assignment.
=> false

num = 7 is always true, because all values except false and nil are
true in the boolean sense in Ruby.
num == 7 is only true when num is 7.

-greg
 
C

CompGeek78

You want an equality check, not assignment.


=> false

num = 7 is always true, because all values except false and nil are
true in the boolean sense in Ruby.
num == 7 is only true when num is 7.

-greg

Oh gads I'm an idiot...thanks.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,776
Messages
2,569,603
Members
45,187
Latest member
RosaDemko

Latest Threads

Top