4 * "test "
TypeError: String can’t be coerced into
Fixnum
from (irb):19:in
`*’
from (irb):19
I understand that ruby being strongly typed means you can only do
“sensible”
things with the types you are working with. However, aren’t the examples
above pretty much equivalent? or is it a precedence thing? Trying to
answer
my own question is it because the “" operator for a Fixnum only accepts
another Fixnum/Bignum, while the "” operator for a String only allows a
Fixnum, because it sure doesn’t let you do String * String (and why
would
you really).
4 * "test "
above pretty much equivalent? or is it a precedence thing? Trying
to answer
my own question is it because the “" operator for a Fixnum only
accepts
another Fixnum/Bignum, while the "” operator for a String only
allows a
Fixnum, because it sure doesn’t let you do String * String (and why
would
you really).
Someone please help me grasp this Thanks
You’ve got it I think. In the first instance you call the String#*
method. This accepts an Integer argument and returns a String:
String * Fixnum works:
…
while Fixnum * String doesn’t:
Think of it like this:
43 = 4+4+4 (4 added 3 times) = 12
34 = 3+3+3+3 (3 added 4 times) = 12
Those are equivalent because x added y times and y added x times always
give
the same result (x and y being numbers).
“bla”*3=“bla”+“bla”+“bla” (“bla” added 3 times)=“blablabla”
But what would 3 * “bla” be? 3 added “bla” times? What does that mean?
4 * "test "
another Fixnum/Bignum, while the “*” operator for a String only allows a
Fixnum, because it sure doesn’t let you do String * String (and why would
you really).
Someone please help me grasp this Thanks
As I read it in Chris P.'s excellent ‘How to Program’, when you do
string * fixnum, you’re telling the string to multiply itself ‘fixnum’
times - the string knows how to do that.
When you do fixnum * string, you’re trying to ask the a fixnum to
multiply itself string times - that makes no sense. Thus, it’s not
allowed.
Cheers,
Mohit.
8/21/2007 | 3:00 PM.
P.S. I’m new to the group - so, I’ll use this email to piggyback and say
HI to everyone!
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.