what does this do?

T

Tony Arcieri

[Note: parts of this message were removed to make it a legal post.]

"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'
 
J

Josh Cheek

[Note: parts of this message were removed to make it a legal post.]

"abcd"[0..2] = 'ggg'
=> "ggg"

What is going on here, anybody have any ideas?
-r

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.
 
C

Colin Bartlett

"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:
http://ruby-doc.org/docs/ProgrammingRuby/html/tut_expressions.html
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?
 

Ask a Question

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

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,163
Messages
2,570,897
Members
47,434
Latest member
TobiasLoan

Latest Threads

Top