Discussion in 'Ruby' started by gerberdata, Jan 26, 2012.

1. ### gerberdataGuest

Can someone explain what is going on in this code
REGEXP = {
:time_in_pain => /\A(\d*\.?\d*)\s*(.+)\Z/,
:number_only => /\A(\d*\.?\d*)\Z/,
:weeks => /\Aw(eek(s)?)?\Z/i,
:months => /\Am(onth(s)?)?\Z/i,
:years => /\Ay(ear(s)?)?\Z/i
}

def time_in_pain=(time_in_pain)
@time_in_pain = time_in_pain.strip
if match = REGEXP[:time_in_pain].match(@time_in_pain)
number, units = match.captures
units.downcase!

units = case units
when REGEXP[:days] then "days"
when REGEXP[:weeks] then "weeks"
when REGEXP[:months] then "months"
when REGEXP[:years] then "years"
else
nil
end

# Use highest possible precision - Float if possible, otherwise
Integer
unless units.nil?
if ["days", "weeks"].include?(units)
self.pain_length_in_days = (number.to_f.send(units) /
1.day).round
else
self.pain_length_in_days = (number.to_i.send(units) / 1.day)
end
end
elsif REGEXP[:number_only].match(@time_in_pain)
self.pain_length_in_days = @time_in_pain.to_i
end
end

gerberdata, Jan 26, 2012

2. ### Robert KlemmeGuest

On 26.01.2012 20:17, gerberdata wrote:
> Can someone explain what is going on in this code
> REGEXP = {
> :time_in_pain => /\A(\d*\.?\d*)\s*(.+)\Z/,
> :number_only => /\A(\d*\.?\d*)\Z/,
> :weeks => /\Aw(eek(s)?)?\Z/i,
> :months => /\Am(onth(s)?)?\Z/i,
> :years => /\Ay(ear(s)?)?\Z/i
> }
>
> def time_in_pain=(time_in_pain)
> @time_in_pain = time_in_pain.strip
> if match = REGEXP[:time_in_pain].match(@time_in_pain)
> number, units = match.captures
> units.downcase!
>
> units = case units
> when REGEXP[:days] then "days"
> when REGEXP[:weeks] then "weeks"
> when REGEXP[:months] then "months"
> when REGEXP[:years] then "years"
> else
> nil
> end
>
> # Use highest possible precision - Float if possible, otherwise
> Integer
> unless units.nil?
> if ["days", "weeks"].include?(units)
> self.pain_length_in_days = (number.to_f.send(units) /
> 1.day).round
> else
> self.pain_length_in_days = (number.to_i.send(units) / 1.day)
> end
> end
> elsif REGEXP[:number_only].match(@time_in_pain)
> self.pain_length_in_days = @time_in_pain.to_i
> end
> end

Looks like someone is superfluously storing Regexp instances in a Hash.
Or is the Hash changed in some other place?

Kind regards

robert

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

Robert Klemme, Jan 27, 2012