Question on do block

Discussion in 'Ruby' started by CompGeek78, Jul 31, 2008.

  1. CompGeek78

    CompGeek78 Guest

    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?
    CompGeek78, Jul 31, 2008
    #1
    1. Advertising

  2. 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
    Gregory Brown, Jul 31, 2008
    #2
    1. Advertising

  3. CompGeek78

    CompGeek78 Guest

    On Jul 31, 12:14 pm, Gregory Brown <> wrote:
    > 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


    Oh gads I'm an idiot...thanks.
    CompGeek78, Jul 31, 2008
    #3
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Showjumper
    Replies:
    1
    Views:
    686
    Showjumper
    Mar 19, 2005
  2. Noozer

    Block DIV within a block DIV?

    Noozer, Jan 6, 2005, in forum: HTML
    Replies:
    3
    Views:
    11,344
    Mitja
    Jan 6, 2005
  3. Andy
    Replies:
    0
    Views:
    519
  4. morrell
    Replies:
    1
    Views:
    926
    roy axenov
    Oct 10, 2006
  5. Alvin
    Replies:
    8
    Views:
    951
Loading...

Share This Page