Created
March 30, 2017 07:11
-
-
Save bparanj/1f719a92ab89c24c11583b33b60b0098 to your computer and use it in GitHub Desktop.
Ruby Object Model Exercise #3
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
character = '' | |
case character | |
when "^" | |
puts 'It is a caret' | |
when ">" | |
puts 'It is a greater than' | |
else | |
puts "You can't even use a computer!" | |
end |
Author
bparanj
commented
Mar 30, 2017
Constraint: Do not use any Ruby case language construct.
class Caser
def initialize
@conditions = Hash.new
end
def add(value, &block)
@conditions[value] = block
end
def at(value)
match = @conditions[value]
if match
match.call
:matched
else
:no_match
end
end
end
# Testing
c = Caser.new
c.add("^") do
puts "It's a caret"
end
c.add(">") do
puts "It's a greater than"
end
c.add("<") do
puts "It's a less than than"
end
puts c.at('<')
puts c.at('>')
puts c.at('^')
puts c.at('*')
class String
DICTIONARY = {
"^" => Proc.new{ puts "it's a carat" },
">" => Proc.new{ puts "it's a greater or less than sign" }
}
def check
if DICTIONARY[self]
DICTIONARY[self].call
else
puts "You can't even use a computer!"
end
end
end
"^".check
">".check
" ".check
class BasicObject
def add(key, &blk)
@my_at||=::Hash.new
@my_at[key] = blk
end
def at(key)
@my_at||=::Hash.new
@my_at[key].call if @my_at[key]
end
end
map = Hash.new
map.add("^") { puts 'It is a caret' }
map.at("&")
map.at("^")
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment