Difference between string operators + and << in Ruby

I am new to Ruby and on this site.

The following two functions are different: one changes the variable outside the function, and the other does not.

def m1 (x)
  x << "4"
end

def m2 (x)
  x = x + "4"
end


str="123"

m2(str)   #str remains unchanged 123

m1(str)   #str is changed to 1234

I would like to make sure I understood correctly -

When m1 is called, the str reference is copied and passed to the function that sees it as x. The operator <changes x that refer to the original str, so this str is modified by this operation.

When m2 is called, the str reference is copied and passed to the function that sees it as x. The + operator creates a new line, and assigning x = x + "4" simply redirects x to a new line, leaving the original str variable intact.

Right?

thank

method declarations and invokation

+5
source share
3 answers

String#+:: str + other_str → new_str - , other_str, str.

     

String#<<:: str << integer → str: - str.

<< , + .

a = "str"
#=> "str"
a.object_id
#=> 14469636
b = a << "ing"
#=> "string"
a.object_id
#=> 14469636
b.object_id
#=> 14469636

a=  "str"
#=> "str"
b = a + "ing"
#=> "string"
a.object_id
#=> 16666584
b.object_id
#=> 17528916

, . . :

def m1 (x)
 x << "4"
end
#=> nil
def m2 (x)
 x = x + "4"
end
#=> nil

str="123"
#=> "123"

m2(str)
#=> "1234"

str
#=> "123"

str m2(), . , str, . , , .

str = m2(str)
#=> "1234"

str
#=> "1234"

: - str, .

str = "abc"
#=> "abc"
str.object_id
#=> 16250484
ObjectSpace._id2ref(16250484)
#=> "abc"
def m1 (x)
ObjectSpace._id2ref(x) << "4"
end
#=> nil
m1(16250484)
#=> "abc4"
str
#=> "abc4"

, :)

!

+10

<< . , , , .

:

str = "abc"
puts str + "d" # "abcd"

puts str # "abc"

puts str << "d" # "abcd"

puts str # "abcd"
+2

The following two functions are different: one changes the variable outside the function, and the other does not.

It is not right. None of the two methods (these are methods, BTW, not functions, Ruby has no functions, there is a fundamental difference) modifies a variable str. m1modifies the object that the variable points to, but is completely different from modifying the variable itself.

+1
source

All Articles