Skip to content

Instantly share code, notes, and snippets.

@baweaver
Created December 1, 2022 22:13
Show Gist options
  • Save baweaver/f96df26efa230e67b90fd4050f9bf027 to your computer and use it in GitHub Desktop.
Save baweaver/f96df26efa230e67b90fd4050f9bf027 to your computer and use it in GitHub Desktop.
class Cond
IDENTITY = -> v { v }
def initialize(if_cond: IDENTITY, then_branch: IDENTITY, else_branch: IDENTITY)
@if_cond = if_cond
@then_branch = then_branch
@else_branch = else_branch
end
def call(v)
@if_cond.call(v) ? @then_branch.call(v) : @else_branch.call(v)
end
alias_method :===, :call
def to_proc
-> v { call(v) }
end
define_method(:if) do |&block|
@if_cond = block
self
end
define_method(:then) do |&block|
@then_branch = block
self
end
define_method(:else) do |&block|
@else_branch = block
self
end
class << self
define_method(:if) do |&block|
new(if_cond: block)
end
define_method(:then) do |&block|
new(then_branch: block)
end
define_method(:else) do |&block|
new(else_branch: block)
end
end
end
(1..5).map(&Cond.if(&:even?).then { _1 * 2 }.else { _1 * 3 })
# => [3, 4, 9, 8, 15]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment