Skip to content

Instantly share code, notes, and snippets.

@britishtea
britishtea / benchmark.rb
Created October 13, 2014 13:43
String#=~ vs String#include? vs String#[]
Benchmark.ips do |x|
x.report { x="str"; x =~ /foo/ || x =~ /bar/ }
x.report { x="str"; x.include?("foo") || x.include?("bar") }
x.report { x="str"; x["foo"] || x["bar"] }
end
@britishtea
britishtea / symbol.rb
Created October 11, 2014 17:17
Two small extensions to `Symbol`.
class Symbol
def [](*args)
proc do |object|
object.send self, *args
end
end
def ~
proc do |object, *args|
object.send self, *args
@britishtea
britishtea / for.rb
Last active August 29, 2015 14:05
Benchmark: #each vs for
require "benchmark"
require "benchmark/ips"
range = Array(1..100_000)
Benchmark.ips do |x|
x.report("each") { range.each { |x| } }
x.report("for") { for x in range; end }
end
require "benchmark"
require "benchmark/ips"
require "dish"
hash = {
title: "My Title",
authors: [
{ id: 1, name: "Mike Anderson" },
{ id: 2, name: "Well D." }
],
@britishtea
britishtea / example.rb
Last active December 31, 2015 16:09
Simple pattern matching in Ruby that won't win any beauty contests.
require 'function'
# A fibonacci function.
fib = Function.new
fib[0] = 0
fib[1] = 1
fib[Integer] = ->(i) { fib[i - 2] + fib[i - 1] }
p fib[0] # => 0
@britishtea
britishtea / example_case.rb
Last active December 25, 2015 12:49
Simple and possibly broken pattern matching in Ruby. Proof of Concept.
require "pattern_matching"
# Let's abuse case statements and the case equality method (#===) to implement
# pattern matching in Ruby.
#
# Note that this'll only work in Ruby 2.1.0-dev (2.0.0-p247 and lower does not
# honour refined #=== in case statements).
using PatternMatching
@britishtea
britishtea / inject.rb
Created October 1, 2013 18:56
Benchmarking Symbol vs Symbol#to_proc for Enumerable#inject
require "benchmark"
require "benchmark/ips"
array = Range.new(1,1_000_000).to_a
Benchmark.bmbm do |x|
x.report("#inject &:*") { array.inject &:* }
x.report("#inject :*") { array.inject :* }
end
module Mixin
def foo
puts "foo"
end
end
class A; end
a = A.new
@britishtea
britishtea / fib.rb
Last active December 20, 2015 01:09
Memoized Fibonacci numbers with Hash default values
Fib = Hash.new { |hash, key| hash[key] = hash[key - 2] + hash[key - 1] }
Fib.merge! 0 => 0, 1 => 1
require 'minitest'
require 'minitest/autorun'
describe Fib do
it 'fibs' do
assert_equal Fib[0], 0
assert_equal Fib[1], 1
object = []
object.object_id # => 70185911630120
hash = Hash.new([])
hash[:one].object_id # => 70185911630120
hash[:two].object_id # => 70185911630120