0

Ruby noob here. I have multiple arrays in a ruby script I want to append to create a single string with key values pairs where each value of an id array matches the equivalent value of an id_desc array like this:

ids = [1234, 2345, 3456]
ids_desc = ["inst1", "inst2", "inst3"]

How can I build the following string exactly as noted from the above arrays:

"The key for id '#{id}' has a value of '#{id_desc}'"

which should output:

"The key for id '1234' has a value of 'inst1'"
"The key for id '2345' has a value of 'inst2'"
etc. 

I can do the following easily enough:

str1 = Array.new
ids.each do |id|
 str1 << "The key for id '#{id}'"
end

however, I'm having trouble identifying how to add "has a value of #{id_desc}" to the end of each of those key mappings. Anyone have any suggestions?

Thanks!

2 Answers 2

1

You can zip ids array if ids and ids_desc have same length:

ids.zip(ids_desc).each do |id, desc|
  str1 << "The key for id #{id} has a value of #{desc}"
end

Or just use Enumerable#each_with_index:

ids.each_with_index do |id, i|
  str1 << "The key for id #{id} has a value of #{ids_desc[i]}"
end

And you can avoid creating str1 array, using Array#map:

ids.zip(ids_desc).map do |id, desc|
  "The key for id #{id} has a value of #{desc}"
end
Sign up to request clarification or add additional context in comments.

Comments

0

Collect Strings

ids = [1234, 2345, 3456]
ids_desc = ["inst1", "inst2", "inst3"]
array = ids.zip(ids_desc).map { |e| "The key for id '%d' has a value of '%s'" % e }

Print Collection to Standard Output

array.map { |e| puts e }

The key for id '1234' has a value of 'inst1'
The key for id '2345' has a value of 'inst2'
The key for id '3456' has a value of 'inst3'

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.