Skip to content

Instantly share code, notes, and snippets.

@bparanj
Created March 30, 2017 07:11
Show Gist options
  • Save bparanj/1f719a92ab89c24c11583b33b60b0098 to your computer and use it in GitHub Desktop.
Save bparanj/1f719a92ab89c24c11583b33b60b0098 to your computer and use it in GitHub Desktop.
Ruby Object Model Exercise #3
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
@bparanj
Copy link
Author

bparanj commented Mar 30, 2017

map := Dictionary new.
map at: $^ put: [Transcript show: 'It is a caret'].
map at: $> put: [Transcript show: 'It is greater than'].
map at: $< put: [Transcript show: 'It is less than']
         :
result := (map at: char) value.

@bparanj
Copy link
Author

bparanj commented Apr 1, 2017

Constraint: Do not use any Ruby case language construct.

@stevenchanin
Copy link

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('*')

@tahngarth825
Copy link

tahngarth825 commented Apr 1, 2017

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

@sysout
Copy link

sysout commented Apr 1, 2017

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