On Tue, Feb 4, 2014 at 2:41 PM, Dave Castellano <lists / ruby-forum.com> wrote:
> Hi,
>
> Can anyone see an obvious reason why
> question.gsub!(/\{#{number_range}\}/, new_num) is not finding the
> existing match in the question?
>
> question = "A {30-45} year old {asthmatic, diabetic, hypertensive}
> {male, .4} presents with blurry vision in the {left} eye. ... "
>
> # Manage number range
> if    question.match(/\{ {0,5}([0-9][0-9]? {0,3}- {0,3}[0-9][0-9]?)
> {0,5}\}/)
>   number_range = question.match(/\{ {0,5}([0-9][0-9]? {0,3}-
> {0,3}[0-9][0-9]?) {0,5}\}/)
>   x1 = question.match(/\{ {0,5}([0-9][0-9]? {0,3}- {0,3}[0-9][0-9]?)
> {0,5}\}/).to_s[1..-2].split('-')
>   new_num = (rand(x1[0].to_i..x1[1].to_i)).to_s
>   question.gsub!(/\{#{number_range}\}/, new_num)
> end
>
> when I "puts number_range" I get {30-45} so it should find the match.
>
> PS any suggestions on refactoring the code would be welcome also as I am
> learning on my own.

How about:

question = "A {30-45} year old {asthmatic, diabetic, hypertensive}
{male, .4} presents with blurry vision in the {left} eye. ... "

if /\{\s*(\d+)\s*-\s*(\d+)\s*\}/ =~ question
  n1 = Integer($1)
  n2 = Integer($2)
  question[/\{\s*(\d+)\s*-\s*(\d+)\s*\}/] = "{#{rand(n1..n2)}}"

  puts question
end

or even

question = "A {30-45} year old {asthmatic, diabetic, hypertensive}
{male, .4} presents with blurry vision in the {left} eye. ... "

if /\{\s*(\d+)\s*-\s*(\d+)\s*\}/ =~ question
  n1 = Integer($1)
  n2 = Integer($2)
  question[/\{(\s*\d+\s*-\s*\d+\s*)\}/, 1] = rand(n1..n2).to_s

  puts question
end

Cheers

robert

-- 
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/