1

I read (in the documentation) how to concatenate the strings of one array with another string:

a = [ "a", "b", "c", "d" ]
a.collect! {|x| x + "!" }
a                          #=>  [ "a!", "b!", "c!", "d!" ]

but what I haven't figured out is how to concatenate the strings of 2 arrays into one. For example:

field_suffix = %w[prev curr]
field_names = %w[_first_name _last_name]

What I'd like to see is this:

["prev_first_name", "curr_first_name", "prev_last_name", "curr_last_name"]

The order doesn't matter. It could be:

["prev_first_name", "prev_last_name", "curr_first_name", "curr_last_name"]
1
  • Thanks for all the answers - they all work great. I accepted JavaNut13's answer because it was first but I actually went back and used megas answer because it seemed the 'sexiest'. I voted all the answers up because they all work. Commented Aug 25, 2012 at 11:47

3 Answers 3

3
field_suffix.product(field_names).map(&:join)
Sign up to request clarification or add additional context in comments.

Comments

1

I would do it with the following:

out=[]
pre=["sub", "pre"]
suf=["less", "ness"]
pre.each do |p|
  suf.each do |s|
    out.push(p+s)
  end
end
puts out

Or in less lines:

out=[]
pre=["sub", "pre"]
suf=["less", "ness"]
pre.each{|p| suf.each{|s| out.push(p+s)}}

This will not return the array (sadly), you have to have the second array; out which will be subless, subness, preless, preness

2 Comments

Thanks for the answer, unfortunately, this gives me out = ["sub","pre"]
See answer, print out array
1

Here it is:

field_suffix = %w[prev curr]
field_names = %w[_first_name _last_name]

result = field_suffix.product(field_names).collect {|suffix, name| suffix + name}

See Array#product for details

Comments

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.