com/ <http://www.ruby-forum.com/>\.
Relying on hash is something I shy from, it is not implemented across all
Rubies. Like Jesus said, the point of a hash is to be able to access the
elements by their keys, rather than indexes. So, given that you know the
question, in your example you would put it into the hash, and the hash would
give you back the answer. That isn't how you are using it, and so things are
weird.
To use it as a hash, just iterate over it:
# simple quiz program
problems={
"Question 1"=>"Answer 1",
"Question 2"=>"Answer 2",
}
score=0
problems.each do |question,answer|
puts question
if gets.chomp == answer
puts "Good answer !"
score+=1
else
puts "Bad answer !"
end
end
puts "Your score is #{score}/#{problems.size}."
···
----------
But I think that is still misleading, since you aren't using it as key/value
pairs. Really, you are using it as an array of arrays, so this is probably
more straighforward:
problems= [
["Question 1","Answer 1"],
["Question 2","Answer 2"],
]
----------
Here is an example showing how you could use hashes with this. Though this
script is simple enough in its current form, that I don't think it is really
necessary.
problems = [
{ :question => "Question 1" , :answer => "Answer 1" },
{ :question => "Question 2" , :answer => "Answer 2" },
]
score=0
problems.each do |problem|
puts problem[:question]
if gets.chomp == problem[:answer]
...
----------
If your data ever gets complicated enough that the above is better than the
array of arrays, then you probably want to start thinking about turning it
into a class. If its just a collection of data, I like to use a struct, then
if it gets complicated enough to need methods, I would later turn it into a
class. Structs are great for carefree prototyping like this.
Problem = Struct.new :question , :answer
problems = [
Problem.new("Question 1","Answer 1"),
Problem.new("Question 2","Answer 2"),
]
score=0
problems.each do |problem|
puts problem.question
if gets.chomp == problem.answer
...