views:

107

answers:

4

I am working on http://rubyquiz.com/quiz28.html and am almost done except for one little bug.

In the following: prompts is an array, which for arguments sake is ["one", "two", "three", "three", "four]

  def ask_reader(prompts)
    @answers = {}
    for p in prompts
      puts "Give me a #{p}"
      @answers[p] = gets.chomp
    end
  end

This works fine and I get an answers hash with the corresponding answers, except that the second answers[p] will override the first one, thus leaving me with only one value for "three". Is there good 'ruby' way of solving this? Thanks.

A: 

What about using as keys some sort of wrapper objects with internal field 'prompt' ?

Dmitry
+4  A: 

how about a map of prompts to lists of values, like this:

prompt1 => ["one"] prompt2 => ["two"] prompt3 => ["three", "three"] prompt4 => ["four"]

+2  A: 

Two obvious options:

Cross-reference the original prompts array with the answers array by means of Array#zip:

def ask_reader(prompts)
  prompts.inject([]) do |accu, p|
    puts "Give me a #{p}"
    accu << gets.chomp
    accu
  end
end

["one", "two", "two"].zip(["1", "2", "3"])
# => [["one", "1"], ["two", "2"], ["two", "3"]]

Then iterate like so:

[["one", "1"], ["two", "2"], ["two", "3"]].each do |(prompt, response)|
  puts "#{prompt}: #{response}"
end

Or, use a Hash with Array values.

def ask_reader(prompts)
  prompts.inject({}) do |accu, p|
    puts "Give me a #{p}"
    (accu[p] ||= []) << gets.chomp
    accu
  end
end
Bob Aman
Thanks, I used the first solution (as It was the most understandable).
MrCheetoDust
A: 

more simple way.

a = %w[one two three four]
h = Hash.new { |hash, key| hash[key] =  a.find_index(key)+1}
p h["one"]
p h["three"]
marocchino