Simple ruby question

I am learning Ruby and when I am trying to work on some sample examples
I
got some strange (may be to me) output can you please explain me why it
is
??

(1 ** 2).to_s *2 is giving output as “1”
but

(1 ** 2).to_s * 2 is giving output as “11”

the above things that I tried in irb shell

(1 ** 2).to_s *2 is giving output as “1”

but

(1 ** 2).to_s * 2 is giving output as “11”

(1**2).to_s results in 1.to_s *2 gives “1” becoz it is interpreted as
radix that is representation of 1 in base 2
the other bit is pretty simple i mean the output as “11”
I hope that clears your question

But when I tried with “1” *2 it is giving output as “11” and the same
output
I am getting even I tried with “1” *2.

Can you please explain me clearly. I am NOT getting…

On Mon, Mar 17, 2008 at 11:10 PM, dhaval [email protected]

the * is both a “unary unarray” operator and a binary multiplication
operator.

*2 is parsed as the former: (1 ** 2).to_s(*2)

  • 2 is parsed as the latter: (1 ** 2).to_s() * 2

-Rob

I would agree with bob but basically when you take a look at source
code of that then i figured out that if * is not passed even then it
would behave in the same way.
(1**2).to_s(2)
this would still give 1
but there is some wierd thing going on with to_i
when you say “3”.to_i(10) outputs 3 with base 10 which is as expected
but
if you say “3”.to_i(2) outputs 0 rather than binary representation of
3. any idea??

On Mar 18, 8:32 pm, Rob B. [email protected]

On Mar 18, 2008, at 11:45 AM, dhaval wrote:

I would agree with bob but basically when you take a look at source
code of that then i figured out that if * is not passed even then it
would behave in the same way.
(1**2).to_s(2)
this would still give 1
but there is some wierd thing going on with to_i
when you say “3”.to_i(10) outputs 3 with base 10 which is as expected
but
if you say “3”.to_i(2) outputs 0 rather than binary representation of
3. any idea??

str.to_i(base) says to interpret ‘str’ as a representation of a number
in base ‘base’. Since “3” doesn’t contain any valid base 2 digits
[0,1], the value is 0 (just like with “hello”.to_i)

You’re looking at Numeric#to_s and String#to_i

-Rob

On Mar 18, 11:32 am, Rob B. [email protected]
wrote:

the * is both a “unary unarray” operator and a binary multiplication
operator.

*2 is parsed as the former: (1 ** 2).to_s(*2)

But 2 is not an array. Is it being coerced into a single element array
to allow the ‘unary unarray’ to proceed w/o error?