[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Question on do block

CompGeek78

7/31/2008 6:08:00 PM

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?
2 Answers

Gregory Brown

7/31/2008 6:14:00 PM

0

On Thu, Jul 31, 2008 at 2:09 PM, CompGeek78 <keven.denen@gmail.com> wrote:

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

>> a = 1
=> 1
>> a == 1
=> true
>> a == 2
=> 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

CompGeek78

7/31/2008 6:17:00 PM

0

On Jul 31, 12:14 pm, Gregory Brown <gregory.t.br...@gmail.com> wrote:
> On Thu, Jul 31, 2008 at 2:09 PM, CompGeek78 <keven.de...@gmail.com> wrote:
> > 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.
>
> >> a = 1
> => 1
> >> a == 1
> => true
> >> a == 2
>
> => 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.