The bigger picture... I am saving multiple question templates in a
array and need to store all the info (the question, the min and max
ranges, the units of measure etc assoc with each question. The
associated info is used to build the question ... eg in question one,
need to pass 20,40 to number_range(min,max) and use the returned value
as u.
Ok...
First: did you consider using a templating system for your
"question templates"? You could avoid the lambdas;
instead, you provide a template as a simple string that gets
evaluated later when the needed values are known.
Second: Instead of using nested arrays I would put all the
question-generating functionality into a class.
Assuming the structure of your questions is always the same,
below is one possible way to do it:
require 'erb'
class Question
attr_reader :unit
def initialize(text, range, unit)
@text = ERB.new(text)
@range = range
@unit = unit
end
def val
rand(@range)
end
def to_s
@text.result(binding)
end
end
questions = [
Question.new('A slide is placed <%= val %> <%= unit %>...',
20..40, 'cm'),
Question.new('An image is in focus <%= val %> <%= unit %>...',
10..15, 'mm')
]
questions.each {|q| puts q }
questions.each {|q| puts q } # results in different values
*BUT:*
- Can't you simply include the unit in the text part?
- Do you really need to have the same question with
different values in the same run of your program?
How about:
questions = [
"A slide is placed #{rand(20..40)} cm...",
"An image is in focus #{rand(10..15)} mm..."
]
questions.each {|q| puts q }
···
Am 17.08.2012 14:15, schrieb Dave Castellano:
def number_range(min,max)
min + rand(max - min + 1) **Thanks!
end
array =[
[ lambda {|u,u_unit| "A slide is placed #{u} #{u_unit} to the left of a
lens...", 20, 40, "cm"],
[ lambda {|v,v_unit| "An image is in focus #{v} #{v_unit} to the right
of a...", 10, 25, "mm],
[....
]
puts array[n][variable returned from number_range method]
--
<https://github.com/stomar/>