Skip to content

Instantly share code, notes, and snippets.

@tompng
Created May 8, 2014 16:51
Show Gist options
  • Save tompng/092cd158fb6b36da62ab to your computer and use it in GitHub Desktop.
Save tompng/092cd158fb6b36da62ab to your computer and use it in GitHub Desktop.
def get patterns
loop do
s = gets
p = patterns.find{|p|p=~s}
return [p, s] if p
end
end
number = /\d+/
word = /[a-z]+/
pattern, text = get [number, word]
case [pattern]
when [number]
puts text.to_i+1
when [word]
puts text.upcase
else
puts 'what!?'
end
@hanachin
Copy link

hanachin commented May 8, 2014

class PatternConverter
  def initialize(pattern, &convert)
    @pattern = pattern
    @convert = convert
  end

  def ===(s)
    @pattern =~ s
  end

  def convert(s)
    @convert[s] if @pattern =~ s
  end
end

converters = [
  PatternConverter.new(/\d+/) {|s| s.to_i + 1 },
  PatternConverter.new(/[a-z]+/) {|s| s.upcase }
]

def get_converted_value(converters)
  loop { gets.tap {|s| converters.find {|c| c === s }.tap {|c| return c.convert(s) if c } } }
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment