Skip to content

Instantly share code, notes, and snippets.

@bparanj
Created March 30, 2017 06:43
Show Gist options
  • Save bparanj/32bbe1d2df7f107a6263db5ed44fa26e to your computer and use it in GitHub Desktop.
Save bparanj/32bbe1d2df7f107a6263db5ed44fa26e to your computer and use it in GitHub Desktop.
Ruby Object Model Exercise #1
(count < 10).if_true { }.if_false{ }
@bparanj
Copy link
Author

bparanj commented Mar 30, 2017

Smalltalk equivalent:

(count < 10)
   ifTrue: [ Transcript show: "Count is less than 10"]
   ifFalse: [ Transcript show: "Count is greater than or equal to 10" ]

@bparanj
Copy link
Author

bparanj commented Apr 1, 2017

count = 0

if (count < 10)
  print "Count is less than 10"
else
  print "Count is greater than or equal to 10"
end

@sysout
Copy link

sysout commented Apr 1, 2017

module IfElse
  def if_true(&blk)
    # if self.class.ancestors.include? TrueClass
    yield if self.is_a? TrueClass
    self
  end

  def if_false(&blk)
    # if self.class.ancestors.include? FalseClass
    yield if self.is_a? FalseClass
    self
  end
end

class TrueClass
  include IfElse
end

class FalseClass
  include IfElse
end

count=1
(count < 10).if_true { puts "True" }.if_false{ puts "False" }

count=100
(count < 10).if_true { puts "True" }.if_false{ puts "False" }

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