0

I'm very new to Ruby and am having some problems concatenating strings within a for loop.

Here is what I have so far

# 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

I'd like response[0] to hold "http://example.com/testOne". However, after the loop executes, response[0] only holds the first letter (h) of my base variable; response holds "http://example.com/testTwo".

I'm thinking this is a simple mistake, but can't find any helpful resources.

1 Answer 1

5

Use Array#<< method

# 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}" means you are assigning in each iteration a new string object to the local variable response. In the last iteration response holds the string object "http://example.com/testTwo". Now response[0] means you are calling the method String#[]. So at index 0 of the string "http://example.com/testTwo", the character present is h, so your response[0] returning 'h'- which is expected as per your code.

The same code can be written in more sweet way :

# 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"]

or

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

or, as Michael Kohl pointed :

response = search.map { |s| "#{base_url}#{s}" }
response # => ["http://example.com/testOne", "http://example.com/testTwo"]
Sign up to request clarification or add additional context in comments.

1 Comment

I would go with map { |s| "#{base_url}#{s}" } instead of using String#+. +1 nonetheless.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.