Skip to content

Instantly share code, notes, and snippets.

View eregon's full-sized avatar

Benoit Daloze eregon

View GitHub Profile
@eregon
eregon / benchmark-block
Last active September 19, 2020 14:07
benchmark block - a prototype to benchmark a block without the block overhead
#!/usr/bin/env ruby
private def benchmark(name = nil, &block)
raise "needs a block" unless block
binding = block.binding
file, line = block.source_location
start_line = line - 1
lines = File.readlines(file)
indent = lines.fetch(start_line)[/^(\s+)/, 1]
@eregon
eregon / 0_core_methods_in_ruby.md
Last active February 19, 2025 10:12
Core library methods defined with Ruby code and with a #source_location file starting with `<internal:`, by Ruby implementation and version
Ruby Core methods written in Ruby Total number of core methods % written in Ruby
CRuby 2.3 3 1637 0.2%
CRuby 2.4 3 1636 0.2%
CRuby 2.5 6 1680 0.4%
CRuby 2.6 5 1767 0.3%
CRuby 2.7 38 1802 2.1%
CRuby 3.0 89 1830 4.9%
CRuby 3.1 112 1884 5.9%
CRuby 3.2 128 1924 6.7%
@eregon
eregon / inline_cext.rb
Created January 28, 2021 14:15
Mixing Ruby code and C extension code in a single file
require 'tmpdir'
require 'rbconfig'
def inline_c_extension(c_code)
Dir.mktmpdir('inline_c_extension') do |dir|
File.write("#{dir}/cext.c", c_code)
File.write("#{dir}/extconf.rb", <<~RUBY)
require 'mkmf'
create_makefile('cext')
RUBY
@kddnewton
kddnewton / json.rb
Last active December 18, 2024 17:34
JSON parser with pattern matching
require "json"
struct = { "a" => 1, "b" => 2, "c" => [1, 2, 3], "d" => [{ "e" => 3 }, nil, false, true, [], {}] }
source = JSON.dump(struct)
tokens = []
index = 0
until source.empty?
tokens <<
@eregon
eregon / stats
Last active September 17, 2025 13:25
#!/usr/bin/env ruby
class Stats
def initialize(data)
@data = data
@sorted = data.sort
end
def size
@data.size