Skip to content

Instantly share code, notes, and snippets.

@baweaver
Last active August 15, 2024 21:45
Show Gist options
  • Save baweaver/471bdfca565a68ddc288eb3bb57c5e10 to your computer and use it in GitHub Desktop.
Save baweaver/471bdfca565a68ddc288eb3bb57c5e10 to your computer and use it in GitHub Desktop.
Very much work in progress, will amend this as I have time. Feel free to comment ideas.

Evolution of a Ruby Programmer

A fun joke based on Evolution of a Haskell Programmer.

Regional Dialects

Came from Seattle

require "minitest/autorun"

def factorial n
  raise ArgumentError, "Out of Range" if n.negative?
  
  if n.zero? then
    1
  else
    result = factorial n - 1
    n * result
  end
end

class TestFactorial < Minitest::Test
  def test_zero
    result = factorial 0
    assert_equal result, 1
  end
  
  def test_five
    result = factorial 5
    assert_equal result, 120
  end
end

Came from Japan

require 'test/unit'

def fac(n)
  if n.negative? then raise ArgumentError, "Out of range" end
  if n.zero? then return 1 end
  
  total = n
  while (n -= 1) > 0
    total *= n
  end
  
  total
end

class FacTest < Test::Unit::TestCase
  def test_failure
    assert_raises { fac(-1) }
  end
  
  def test_zero
    assert(fac(0) == 1)
  end
  
  def test_five
    assert(fac(5) == 120)
  end
end

Came from San Francisco

require "rspec/autorun"

def factorial(n) = n.zero? ? 1 : n * factorial(n - 1)
  
RSpec.describe "#factorial" do
  let(:result) { factorial(n) }
  
  context "When given 0" do
    let(:n) { 0 }
    
    it "should equal 1" do
      expect(result).to eq(0)
    end
  end
  
  context "When given 5" do
    let(:n) { 5 }
    
    it "should equal 120" do
      expect(result).to eq(120)
    end
  end
  
  # TODO: go/jira/FACT-1234 - Handle negatives
  xcontext "When given a negative number" do
  end
end

Came from Quines

($_=->_{@_=$$/$$;_<=@_?@_:_*$_[_-@_]})[5]

Influenced By

Rails

class Numeric
  def fibonacci
    raise ArgumentError, "Out of bounds" if negative?
    
    (1..self).reduce(:*)
  end
end

5.fibonacci

DryRB

require 'dry/monads'
extend Dry::Monads[:result]

def fibonacci(n)
  return Failure("Out of bounds") if n.negative?
  
  Success((1..n).reduce(:*))
end

MemoWise

gem 'memo_wise'

prepend MemoWise

memo_wise def fibonacci(n)
  raise ArgumentError, "Out of bounds" if n.negative?

  (1..n).reduce(:*)
end
@corsonknowles
Copy link

As I feel deeply seen by the San Franciso entry (using RSpec), I also wanted to fill in the missing characters in the code golf approach.

It needs an n * i.e. It should read:

def factorial(n) = n.zero? ? 1 : n * factorial(n - 1)

As first written, it will always return 1 for non-negative numbers.

Both the original and the fixed version will cause a stack overflow for any negative number (since we don't believe in ArgumentErrors, I guess!)

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