【问题标题】:Trying to understand the shovel operator with strings试图用字符串理解铲子运算符
【发布时间】:2018-03-31 21:58:15
【问题描述】:

我正在通过http://rubykoans.com/

在 koans/about_strings.rb:100 文件中

  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

这通过了,虽然我认为 original_string 将等于“Hello”,而 hi 将等于“Hello, World”

我看到这张海报有一个类似的问题,但不完全是:

Why is the shovel operator (<<) preferred over plus-equals (+=) when building a string in Ruby?

我错过了什么?

【问题讨论】:

  • 谁创造了“铲子操作员”这个词?
  • 我不确定我是否见过用于连接字符串的铲子运算符。一些更常见的技术是"#{hi}#{there}"[hi, there].join
  • 再次查看第 3 行:在第 3 行中,您告诉 Ruby 使它们相同!因此,它们相同的。

标签: ruby string


【解决方案1】:

当您设置hi = original_string 时,您的hi 变量只是指向同一对象的新变量。如果您查看hi.object_idoriginal_string.object_id,您会发现它们是相同的。如果您想要一个可以在不影响对象的情况下进行操作的对象的克隆 original_string,你需要说类似hi = original_string.clonehi = original_string.dup

【讨论】:

    猜你喜欢
    • 2016-01-01
    • 2015-06-15
    • 1970-01-01
    • 2011-06-08
    • 2020-02-11
    • 2021-04-16
    • 1970-01-01
    • 2016-10-27
    • 2012-03-09
    相关资源
    最近更新 更多