1

So say I have a 2D array like this:

list = [["auburn", "http://auburn.craigslist.org"], ["birmingham", "http://bham.craigslist.org"], ["dothan", "http://dothan.craigslist.org"]]

I would like it to look like this:

list = [["auburn", "http://auburn.craigslist.org/web/"], ["birmingham", "http://bham.craigslist.org/web/"], ["dothan", "http://dothan.craigslist.org/web/"]]

So I have just modified the second element within each nested array.

How do I do that in Ruby?

Thanks.

2 Answers 2

3

Try this

list.map!{|f,l| [f, l + "/web/"]}
Sign up to request clarification or add additional context in comments.

2 Comments

This works...but another thing I am trying to do is to add another to each list element with another url modified with the ending /bk/ for instance. So list would then be [0] = text, [1] = url.com/web/,[2] = url.com/bk/. How can I do that here?
This should do: list.map!{|f,l| [f, l + "/web/", l + "/bk/"]}
1

list.map! { |elem| [elem[0], elem[1] << '/web/'] }

2 Comments

This works wonders...one question...so basically I want to capture each URL in elem[1] before it is modified...which I will then use as the base for another URL in elem[2]. How do I do that? I tried setting a local variable to be elem[1] before I append /web/ to it, but it still gives me the modified URL for elem[2] instead of the pre-modified one. i.e. I am getting url.com/web/ instead of just url.com.
This creates a new list AND modifies the existing one. If you want to modify the (strings in the) existing list, don't use map, just use each.

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.