我正在寻找一种更优雅的方式来连接Ruby中的字符串.
我有以下几行:
source = "#{ROOT_DIR}/" << project << "/App.config"
Run Code Online (Sandbox Code Playgroud)
这样做有更好的方法吗?
就此而言,<<和之间的区别是+什么?
我记得曾经一度骂过用Python连接字符串.有人告诉我,在Python中创建一个字符串列表并在以后加入它们会更有效.我把这种做法带到了JavaScript和Ruby中,虽然我不确定它在后者中是否具有相同的好处.
任何人都可以告诉我,加入一个字符串数组并调用它是否更有效(资源和执行):加入它们或者根据需要在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,但我想知道为什么没有方法 +=
那么只是修改原始字符串的铲子操作符吗?为什么这样做,它看起来像:
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) 以这段代码为例:
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.newt.run它会输出这个错误:
NoMethodError: undefined method `+' for nil:NilClass
Run Code Online (Sandbox Code Playgroud)
如果删除+=线(只留下return线),它返回[]......所以从我可以告诉,它只是存在+=,设置list到nil.我也觉得有趣的是它的值nil …