“abcd”[0…2] = ‘ggg’
=> “ggg”
What is going on here, anybody have any ideas?
-r
“abcd”[0…2] = ‘ggg’
=> “ggg”
What is going on here, anybody have any ideas?
-r
On Mon, Dec 14, 2009 at 3:23 PM, Roger P. [email protected]
wrote:
“abcd”[0…2] = ‘ggg’
=> “ggg”What is going on here, anybody have any ideas?
Ruby lets you invoke #[]= on literals. They then go immediately out of
scope and will be garbage collected, I assume. #[]= will always return
the
value on the RHS.
Perhaps this clears things up:
=> “abcd”
x[0…2] = ‘ggg’
=> “ggg”
x
=> “gggd”
So that’s what would happen if you used a variable instead of a literal.
What you’re doing isn’t much different from:
{:foo => 42}[:foo] = ‘ggg’
On Mon, Dec 14, 2009 at 4:23 PM, Roger P. [email protected]
wrote:
“abcd”[0…2] = ‘ggg’
=> “ggg”What is going on here, anybody have any ideas?
-rPosted via http://www.ruby-forum.com/.
var = “abcd” # => “abcd”
var[0…2] = ‘ggg’ # => “ggg”
var # => “gggd”
It just replaces indexes 0 through 2 with the string “ggg” When you
assign
it to a variable, it is easier to see.
It returned “ggg” in irb (as seen on the second line) because it was
assigned through the equal sign, and assignments through equal signs
always
return whatever the input was.
Tony A. wrote:
On Mon, Dec 14, 2009 at 3:23 PM, Roger P. [email protected]
wrote:“abcd”[0…2] = ‘ggg’
=> “ggg”What is going on here, anybody have any ideas?
Ruby lets you invoke #[]= on literals.
Thanks for your and Josh’s replies. It makes sense now.
“abcd”[0…2] = ‘ggg’
is replacing abc with ggg – it’s just that the result isn’t stored
anywhere
-r
On Tue, Dec 15, 2009 at 3:31 PM, Roger P. [email protected]
wrote:
On Mon, Dec 14, 2009 at 3:23 PM, Roger P. [email protected]
wrote:“abcd”[0…2] = ‘ggg’
=> “ggg”
What is going on here, anybody have any ideas?
I hesitate to add to the above replies, but I might learn something, so:
IRB
class Q
def z=( v ) ; @y = 42 ; end
def y() ; @y ; end
end
#=> nil
q = Q.new #=> #<Q:0x4484dd4>
q.y #=> nil
q.z = 113 #=> 113
q.y = #=> 42
q #=> #<Q:0x4524d84 @y=42>
From Programming Ruby, 1st Edition, 2000, page 76:
Programming Ruby: The Pragmatic Programmer's Guide
An assignment statement sets the variable or attribute on its left
side (the lvalue)
to refer to the value on the right (the rvalue).
It then returns that value as the result of the assignment expression.
“abcd”[0…2] = ‘ggg’
is an assignment expression, and the rvalue is “ggg”, so that’s what’s
returned.
Whilst usually (but not always, as in the Q example above)
the assignment “sets” the lvalue target to the rvalue,
that’s (sort of) “irrelevant” to what the assignment expression returns?
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.
Sponsor our Newsletter | Privacy Policy | Terms of Service | Remote Ruby Jobs