Skip to content

Instantly share code, notes, and snippets.

require 'benchmark'
n = 100_000
ar = [4,5,6,4,5,6,6,7]
Benchmark.bm(15) do |b|
b.report("Ralph Shneiver:"){ n.times { result = Hash.new(0); ar.each { |x| result[x] += 1 }; result} }
b.report("Sigurd:") { n.times { ar.inject(Hash.new(0)) {|res, x| res[x] += 1; res } } }
b.report("Keinich #1") { n.times { Hash[ar.group_by{|n|n}.map{|k,v|[k, v.size]}] } }
b.report("Keinich #2") { n.times { Hash.new(0).tap{|h|ar.each{|n|h[n] += 1}} } }
b.report("Magnus Holm:") { n.times { ar.each_with_object(Hash.new(0)) { |x, res| res[x] += 1 } } }
@abinoam
abinoam / regexp_bug_investigation.rb
Created January 21, 2012 02:50
Testing for a possible regexp bug on 1.9.2-290
#!/usr/bin/env ruby
regexp = /^([A-Z]{1,4})([0-9]{1,4})$/
text_phrases =
[ "ABCD1234",
"ABCDE1234",
"ABCD12345",
"ABCDE12345"]
@abinoam
abinoam / append_data_to_daily_files.rb
Last active December 17, 2015 00:39
append_data_to_daily_files - Ruby Talk
def append_data_to_daily_files
Dir.entries('A').each do |file|
next unless file.match(/today/i)
File.open(File.join("A",file), 'a') do |file|
file.puts("hello")
end
end
end
require 'psych'
class ScalarHandler < Psych::Handler
def parser=(parser)
@parser=parser
end
def mark
@parser.mark
#!/usr/bin/env ruby
def the_main_script
# Your main script
# Do whatever here
x = rand(3)
puts "x = #{x}"
puts "and 10/#{x} = #{10/x}" # When x==0 ZeroDivisionError
end
class MegaLotto
NUMBERS = 5
def draw
Array.new(NUMBERS){ single_draw }
end
private
def single_draw
#!/usr/bin/env ruby
# If no local variable is found,
# it begins the method lookup that ends calling
# the method_missing chain until the last one raises the error
begin
p undefined_name if true
rescue
puts "Raised an error"
#!/usr/bin/env ruby
#coding: utf-8
def del_first_three_original_1(a)
num_to_del = a.find { |e| a.count(e) >= 3 }
return a if num_to_del.nil?
3.times do
ind = a.index { |e| e == num_to_del }
a.delete_at(ind)
end
@abinoam
abinoam / encoding.rb
Last active August 29, 2015 14:02
https://www.ruby-forum.com/topic/4980931 - Gist of an irb session messing around with encodings
file = File.open "acao_e_reacao_utf16_le.txt"
=> #<File:acao_e_reacao_utf16_le.txt>
file.methods.grep /enc/
=> [:external_encoding, :internal_encoding, :set_encoding]
file.external_encoding
=> #<Encoding:UTF-8>
file.internal_encoding
module FactoryGirl::Syntax::Methods
def find_or_create(name, attributes = {}, &block)
factory = FactoryGirl.factory_by_name(name)
clazz = factory.build_class
factory_attributes = FactoryGirl.attributes_for(name)
attributes = factory_attributes.merge(attributes)
clazz.find_or_create_by(attributes, &block)
end