Ruby - 在循环中连接数组元素的问题

Kyl*_*ger 0 ruby for-loop

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

我想要回复[0]来保存" http://example.com/testOne ".但是,循环执行后,response [0]只保存我的基本变量的第一个字母(h); 响应持有" http://example.com/testTwo ".

我认为这是一个简单的错误,但找不到任何有用的资源.

Aru*_*hit 5

使用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"]
Run Code Online (Sandbox Code Playgroud)

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

要么

response = search.map(&base_url.method(:+))
response # => ["http://example.com/testOne", "http://example.com/testTwo"]
Run Code Online (Sandbox Code Playgroud)

或者,正如Michael Kohl指出的那样:

response = search.map { |s| "#{base_url}#{s}" }
response # => ["http://example.com/testOne", "http://example.com/testTwo"]
Run Code Online (Sandbox Code Playgroud)

  • 我会选择`map {| s | "#{base_url}#{s}"}`而不是使用`String#+`.尽管如此. (3认同)