Stefano Crocco
1/5/2007 9:47:00 AM
Alle 10:30, venerdì 5 gennaio 2007, Arfon Smith ha scritto:
> Hi, I'm sorry to be asking such a daft question but I need a concept
> explaining....
>
>
> I'm working through the excellent Chris Pine book 'Learn to program' and
> I don't get one of the examples he gives. In particular I don't follow
> the following example:
>
>
> def say_moo number_of_moos
> puts 'mooooooo...' * number_of_moos
> 'yellow submarine'
> end
>
> x = say_moo 3
> puts x.capitalize + ', dude...'
> puts x + '.'
>
> Now the output from this is:
>
> mooooooo...mooooooo...mooooooo
> Yellow submarine, dude...
> yellow submarine
>
> -------------
>
> OK, so here's the problem, I _don't_ get why it doesn't return the
> following:
>
>
> mooooooo...mooooooo...mooooooo
> Yellow submarine, dude...
> mooooooo...mooooooo...mooooooo
> yellow submarine
>
> -------------
>
> Why do we get one set of 'moos' but not a second?
>
> Sorry for such a newbiee question.
>
> Cheers
>
> arfon
say_moo does two separate things:
1- writes the string 'mooooooo...' on the screen number_of_moos times
2- returns the string 'yellow submarine'
The call to puts in the definition of say_moo has nothing to do with say_moo's
return value, which is determinated by the method's last line: 'yellow
submarine'.
Writing x=say_moo 3 will put in x only the string 'yellow submarine', because
this is what say_moo returns. In other words, the line
mooooooo...mooooooo...mooooooo is written by a side effect of say_moo; the
other two lines are produced by your own puts statements.
To get the output you expected (well, not exactly, captialize would work a
little differently), say_moo should have defined like this:
def say_moo number_of_moos
mooooooo...' * number_of_moos+"\nyellow submarine"
end
In this case, say_moo wouldn't write nothing on the screen by itself, but
would return the string
"mooooooo...mooooooo...mooooooo
yellow submarine"
which would be written twice by your puts statements
I hope this helps
Stefano