I would like to explain the behavior in Ruby that I met in Koans

So is it just a spade operator that modifies the original string? Why it works, it looks like this:

hi = original_string 

acts like some kind of pointer? Can I get an idea of ​​when and how and why it behaves this way?

  def test_the_shovel_operator_modifies_the_original_string original_string = "Hello, " hi = original_string there = "World" hi << there assert_equal "Hello, World", original_string # THINK ABOUT IT: # # Ruby programmers tend to favor the shovel operator (<<) over the # plus equals operator (+=) when building up strings. Why? end 
+6
source share
3 answers

In ruby ​​everything is a link. If you do foo = bar , now foo and bar are two names for the same object.

If, however, you execute foo = foo + bar (or, equivalently, foo += bar ), foo now refers to a new object: one that is the result of evaluating foo + bar .

+8
source

acts like some kind of pointer

It is called referential semantics. As in Python, Ruby variables refer to values, not their contents. This is normal for dynamically typed languages, since it is much easier to implement the logic “values ​​are of type, variables are not”, when a variable is always just a reference, and not something that should magically resize to store different types of values.

As for the actual koan, see Why is the scoop operator (<<) preferred over plus values ​​(+ =) when building a string in Ruby? .

+3
source

The string is only a sequence of characters os, <the operator allows you to add a few more characters to this sequence. Some languages ​​have immutable strings, such as Java and C #, others have mutable strings, such as C ++, there is nothing wrong with that, this is what, according to the developers of the language, was necessary.

In Java, when you need to create a large string by combining many smaller strings, you must first use StringBuilder, and then build a real string from it at the end. In Ruby, you can simply continue to use << to add more characters and them to this line.

The main difference is that using <<is much faster than "one_string + other_string" because the + operator generates a new line instead of appending to one_string .

+2
source

Source: https://habr.com/ru/post/907446/


All Articles