Duplicates in hash
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.
how about a map of prompts to lists of values, like this:
prompt1 => ["one"] prompt2 => ["two"] prompt3 => ["three", "three"] prompt4 => ["four"]
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
What about using as keys some sort of wrapper objects with internal field 'prompt' ?
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"]
精彩评论