我是Ruby的新手,在for循环中连接字符串时遇到一些问题。
这是我到目前为止所拥有的
# search request
search = ["testOne", "testTwo"]
# Create base url for requests in loop
base_url = "http://example.com/"
# create an empty response array for loop below
response = []
search.each do |element|
response = "#{base_url}#{element}"
end
我希望response [0]保持“ http://example.com/testOne ”。但是,在循环执行后,response [0]仅保存我的基本变量的第一个字母(h);响应中包含“ http://example.com/testTwo ”。
我认为这是一个简单的错误,但是找不到任何有用的资源。
使用Array#<<
方法
# search request
search = ["testOne", "testTwo"]
# Create base url for requests in loop
base_url = "http://example.com/"
# create an empty response array for loop below
response = []
search.each do |element|
response << "#{base_url}#{element}"
end
response # => ["http://example.com/testOne", "http://example.com/testTwo"]
response = "#{base_url}#{element}"
表示在每次迭代中给局部变量 分配一个新的字符串对象response
。在最后一次迭代中response
保存字符串对象"http://example.com/testTwo"
。现在response[0]
意味着您正在调用该方法String#[]
。因此,在字符串的索引 0
处"http://example.com/testTwo"
,当前字符为h
,因此您的response[0]
返回'h'
-根据您的代码,这是预期的。
相同的代码可以用更甜美的方式编写:
# search request
search = ["testOne", "testTwo"]
# Create base url for requests in loop
base_url = "http://example.com/"
response = search.map {|element| base_url+element }
response # => ["http://example.com/testOne", "http://example.com/testTwo"]
或者
response = search.map(&base_url.method(:+))
response # => ["http://example.com/testOne", "http://example.com/testTwo"]
或者,正如Michael Kohl指出的那样:
response = search.map { |s| "#{base_url}#{s}" }
response # => ["http://example.com/testOne", "http://example.com/testTwo"]
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句