Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Ruby > Question on do block

Reply
Thread Tools

Question on do block

 
 
CompGeek78
Guest
Posts: n/a
 
      07-31-2008
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?
 
Reply With Quote
 
 
 
 
Gregory Brown
Guest
Posts: n/a
 
      07-31-2008
On Thu, Jul 31, 2008 at 2:09 PM, CompGeek78 <> 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

 
Reply With Quote
 
 
 
 
CompGeek78
Guest
Posts: n/a
 
      07-31-2008
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.
 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Fo:Block can you check to see if a block contains any text by using the block id? morrell XML 1 10-10-2006 07:18 PM
Problem with enterprise application block - data block Showjumper ASP .Net 1 03-19-2005 03:48 PM
Block DIV within a block DIV? Noozer HTML 3 01-06-2005 10:24 PM
XML schema validation of one xml block based on values from another xml block Andy XML 0 11-18-2004 11:04 PM



Advertisments
 



1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57