相关疑难解决方法(0)

Ruby中的字符串连接

我正在寻找一种更优雅的方式来连接Ruby中的字符串.

我有以下几行:

source = "#{ROOT_DIR}/" << project << "/App.config"
Run Code Online (Sandbox Code Playgroud)

这样做有更好的方法吗?

就此而言,<<和之间的区别是+什么?

ruby string-concatenation

351
推荐指数
10
解决办法
54万
查看次数

Ruby - Array.join与String Concatenation(效率)

我记得曾经一度骂过用Python连接字符串.有人告诉我,在Python中创建一个字符串列表并在以后加入它们会更有效.我把这种做法带到了JavaScript和Ruby中,虽然我不确定它在后者中是否具有相同的好处.

任何人都可以告诉我,加入一个字符串数组并调用它是否更有效(资源和执行):加入它们或者根据需要在Ruby编程语言中连接一个字符串?

谢谢.

ruby

20
推荐指数
2
解决办法
9550
查看次数

+ =和<<之间的Ruby差异以连接字符串

关于Ruby 1.8.7时发现,似乎有巨大区别的我在做一个循环连接字符串<<+=一对String对象:

 y = ""
 start = Time.now
 99999.times { |x| y += "some new string"  }
 puts "Time: #{Time.now - start}"
 # Time: 31.56718

 y=''
 start = Time.now
 99999.times { |x| y << "some new string"  }
 puts "Time: #{Time.now - start}"
 # Time: 0.018256
Run Code Online (Sandbox Code Playgroud)

我谷歌了解一下,发现了一些结果:

http://www.rubylove.info/post/1038516765/difference-between-string-concatenation-ruby-rails

<<修改两个字符串,而+=只修改调用者.我不明白为什么然后<<更快.

接下来我去了Ruby doc,但我想知道为什么没有方法 +=

http://ruby-doc.org/core-2.2.0/String.html

ruby string

8
推荐指数
1
解决办法
7296
查看次数

我想要解释我在Koans中遇到的Ruby中的行为

那么只是修改原始字符串的铲子操作符吗?为什么这样做,它看起来像:

hi = original_string
Run Code Online (Sandbox Code Playgroud)

表现得像某种指针?我可以获得一些关于何时以及如何以及为何如此行为的见解?

  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
Run Code Online (Sandbox Code Playgroud)

ruby

7
推荐指数
1
解决办法
548
查看次数

为什么+ =将其运行的变量的值重置为nil?

以这段代码为例:

class Thing
  attr_accessor :options, :list

  def initialize
    @list    = []
    @options = { published_at_end: 'NOW', published_at_start: 'NOW-2DAYS' }
  end

  def run
    # If you replace this comment with a debugger, the value of list is nil
    list += _some_method(options)
    return list
  end

  private

  def _some_method(options)
    [options[:published_at_start], 1, 2, 3, 4, options[:published_at_end]]
  end
end
Run Code Online (Sandbox Code Playgroud)

如果将其复制/粘贴到irb中,则运行:

  • t = Thing.new
  • t.run

它会输出这个错误:

NoMethodError: undefined method `+' for nil:NilClass
Run Code Online (Sandbox Code Playgroud)

如果删除+=线(只留下return线),它返回[]......所以从我可以告诉,它只是存在+=,设置listnil.我也觉得有趣的是它的值nil …

ruby

3
推荐指数
1
解决办法
108
查看次数

标签 统计

ruby ×5

string ×1

string-concatenation ×1