question about regexp

G

gerberdata

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/,
:days => /\Ad(ay(s)?)?\Z/i,
: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
 
R

Robert Klemme

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/,
:days => /\Ad(ay(s)?)?\Z/i,
: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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,020
Latest member
GenesisGai

Latest Threads

Top