开发者

Why doesn't this work if in Ruby everything is an Object?

Considering that in the Ruby programming language everything is said to be an Object, I safely assumed that passing arguments to methods are done by reference. However this little example below puz开发者_如何学Gozles me:

$string = "String"

def changer(s)
  s = 1
end

changer($string)

puts $string.class
String
 => nil

As you can see the original Object wasn't modified, I wish to know why, and also, how could I accomplish the desired behavior ie. Getting the method to actually change the object referenced by its argument.


The way Ruby works is a combination of pass by value and pass by reference. In fact, Ruby uses pass by value with references.

You can read more in the following threads:

  • Pass by reference or pass by value
  • Pass by reference?

Some notable quotes:

Absolutely right: Ruby uses pass by value - with references.

irb(main):004:0> def foo(x) x = 10 end
=> nil
irb(main):005:0> def bar; x = 20; foo(x); x end
=> nil
irb(main):006:0> bar
=> 20
irb(main):007:0>

There is no standard way (i.e. other than involving eval and metaprogramming magic) to make a variable in a calling scope point to another object. And, btw, this is independent of the object that the variable refers to. Immediate objects in Ruby seamlessly integrate with the rest (different like POD's in Java for example) and from a Ruby language perspective you don't see any difference (other than performance maybe). This is one of the reasons why Ruby is so elegant.

and

When you pass an argument into a method, you are passing a variable that points to a reference. In a way, it's a combination of pass by value and pass by reference. What I mean is, you pass the value of the variable in to the method, however the value of the variable is always a reference to an object.

The difference between:

def my_method( a )
  a.gsub!( /foo/, 'ruby' )
end

str = 'foo is awesome'
my_method( str )            #=> 'ruby is awesome'
str                                    #=> 'ruby is awesome'

and:

def your_method( a )
  a = a.gsub( /foo/, 'ruby' )
end

str = 'foo is awesome'
my_method( str )            #=> 'ruby is awesome'
str                                    #=> 'foo is awesome'

is that in #my_method, you are calling #gsub! which changes the object (a) in place. Since the 'str' variable (outside the method scope) and the 'a' variable (inside the method scope) both have a "value" that is a reference to the same object, the change to that object is reflected in the 'str' variable after the method is called. In #your_method, you call #gsub which does not modify the original object. Instead it creates a new instance of String that contains the modifications. When you assign that object to the 'a' variable, you are changing the value of 'a' to be a reference to that new String instance. However, the value of 'str' still contains a reference to the original (unmodified) string object.

Whether a method changes the reference or the referenced object depends on the class type and method implementation.

string = "hello"

def changer(str)
  str = "hi"
end

changer(string)
puts string
# => "hello"

string is not changed because the assignment on strings replaces the reference, not the referenced value. I you want to modify the string in place, you need to use String#replace.

string = "hello"

def changer(str)
  str.replace "hi"
end

changer(string)
puts string
# => "hi"

String is a common case where the most part of operations works on clones, not on the self instance. For this reason, several methods have a bang version that executes the same operation in place.

str1 = "hello"
str2 = "hello"

str1.gsub("h", "H")
str2.gsub!("h", "H")

puts str1
# => "hello"
puts str2
# => "Hello"

Finally, to answer your original question, you cannot change a String. You can only assign a new value to it or wrap the string into a different mutable object and replace the internal reference.

$wrapper = Struct.new(:string).new
$wrapper.string = "String"

def changer(w)
  w.string = 1
end

changer($wrapper)

puts $wrapper.string
# => 1


Assignment does not bind values to objects, it binds object references to identifiers. Argument passing works the same way.

When you enter the body of the function, the world looks like this:

 +---+                  +----------+
 | s |----------------->| "String" |
 +---+                  +----------+
                              ^
 +-------+                    |
 |$string|--------------------+
 +-------+

The code

 s = 1

makes the world look like

 +---+       +---+      +----------+
 | s |------>| 1 |      | "String" |
 +---+       +---+      +----------+
                              ^
 +-------+                    |
 |$string|--------------------+
 +-------+

The assignment syntax manipulates variables, not objects.

Like many similar languages (Java, C#, Python) ruby is pass-by-value, where the values are most often references.

To manipulate the string object, you can use a method on the string, such as s.upcase!. This sort of thing will be reflected outside of the method as it manipulate the object itself.


Because both $string and s are references to the same object, the string "String". However, when you assign s to 1, you don't change the object "String", you make it reference a new object.


Ruby passes values around to functions, and these values are references to objects. In your function you are reassigning s to another value, in this case a reference to 1. It does not modify the original object.

Your method isn't changing the object passed in, you're changing what s refers to.


Actually, most managed programming languages like java , c#... almsot all do not pass by reference...

They all pass the reference by value ... that means they make another reference that point to the same object ... assigning it with a new value won't change the value of the original reference ... just what s points to ...

Besides, strings are immutable in most langs, meaning that you cannot change the value after being created.. they have to be recreated as new ones... so you will never see any change in the actual string ...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜