Robert Klemme
1/28/2009 6:51:00 AM
On 28.01.2009 00:31, Tsunami Script wrote:
> I have the following code snippet :
>
> def call(char,value)
> case char
> when " ","#","!","@","$","%","^","&","*","(",")","{","}","
> [","]","\'","\"","<",">",",",".","?",";","\n","\r"
> @map[char].call(value)
> when "digit"
> @map[char].call(value)
> when "char"
> @map[char].call(value)
> else
> puts "don't know what to do with #{char} and #{value}"
> end
> end
>
> can the first when be written in a simpler way ?
PATTERN = [
" ","#","!","@","$","%","^","&","*","(",")","{","}",",",
"digit", "char"
].freeze
def call(char, value)
if PATTERN.include? char
@map[char].call(value)
else
puts "don't know what to do with #{char} and #{value}"
end
end
Or, even more efficient
PATTERN2 = Regexp.new("\\A#{Regexp.union(PATTERN)}\\z")
def call(char, value)
if PATTERN2 =~ char
@map[char].call(value)
else
puts "don't know what to do with #{char} and #{value}"
end
end
Or, even better (i.e. if @map is filled properly)
def call(char, value)
c = @map[char]
if c
c.call(value)
else
puts "don't know what to do with #{char} and #{value}"
end
end
Cheers
robert
--
remember.guy do |as, often| as.you_can - without end