TheOneTrueMorty
TheOneTrueMorty

Reputation: 159

Appending to the same string with different arrays in Ruby

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!

Upvotes: 0

Views: 51

Answers (2)

Todd A. Jacobs
Todd A. Jacobs

Reputation: 84343

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'

Upvotes: 0

Ilya
Ilya

Reputation: 13477

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

Upvotes: 1

Related Questions