Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@wayne5540
Last active September 25, 2022 19:58
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wayne5540/a827b7ac100a934186199008cff51276 to your computer and use it in GitHub Desktop.
Save wayne5540/a827b7ac100a934186199008cff51276 to your computer and use it in GitHub Desktop.
Ruby implementation for Elixir cond
defmodule Validator do
def validate_age(age) do
cond do
age < 18 -> "Under 18"
age < 21 -> "Under 21"
true -> "Adult"
end
end
end
class Elixir
def cond(*assertions)
return assertions.compact.first
end
def if(assertion, block)
return block.call() if assertion == true
end
end
RSpec.describe Elixir do
let(:elixir) { described_class.new }
describe "cond" do
specify do
result = elixir.cond(
elixir.if(false, -> { return 1 }),
elixir.if(true, -> { return 2 }),
elixir.if(true, -> { return 3 })
)
expect(result).to eq(2)
end
end
describe "if" do
specify do
result = elixir.if(true, -> { 1 })
expect(result).to eq(1)
end
specify do
result = elixir.if(false, -> { 1 })
expect(result).to eq(nil)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment