Skip to content

Instantly share code, notes, and snippets.

begin
# prompt> gem install enumerable_lz
require 'enumerable_lz'
rescue LoadError
# prompt> gem install enumerable-lazy if ruby --version < '2.0.0'
require 'enumerable/lazy' if RUBY_VERSION < '2.0'
module Enumerable
def transform &block;lazy.map(&block);end
end
end
@havenwood
havenwood / hash_or_enum.rb
Last active December 12, 2015 05:08
Hash or Enum?
array = [1, 2, 3, 4]
# So...
Hash[*array].map { |k, v| "#{k} - #{v}<br>" }.join
# versus
array.each_slice(2).map { |s| s.join(' - ') }.join '<br>'
@havenwood
havenwood / ditch.rb
Created January 30, 2013 21:28
Ditch a Line (#ruby IRC)
class String
def ditch_line ditched_line
self.split("\n").delete_if { |line| line == ditched_line }.join("\n")
end
end
"Hello there\nGoodbye now\nCome again".ditch_line 'Hello there'
#=> "Goodbye now\nCome again"
@plexus
plexus / wikitable.rb
Created December 29, 2012 14:32
Naive parsing/generating off Mediawiki tables. I use this for automating some Wikipedia edits.
# -*- coding: utf-8 -*-
class WikiTable
attr_accessor :rows, :attributes
class Row
attr_accessor :cells, :attributes
def initialize
@cells = []
end
def <<(c); cells << c ; end
@havenwood
havenwood / naked_hash.rb
Last active December 10, 2015 05:18
naked hash example (irc)
class Dictionary
attr_reader :entries
def initialize
@entries = {}
end
def add naked_hash
naked_hash.each do |k, v|
@entries[k] = v
@plexus
plexus / proxy.rb
Created November 22, 2012 13:18
Minimal TCP/HTTP proxy. Useful for debugging web services.
#!/usr/bin/ruby
require 'socket'
require 'thread'
require 'optparse'
require 'tmpdir'
class ProxyServer
attr_reader :switches
attr_reader :listen_port, :remote_host, :remote_port
@taq
taq / symbol_array.rb
Created November 3, 2012 18:47
Ruby 2.0 symbol array literal
p [:ruby, :"2.0", :symbol, :array, :literal]
#=> [:ruby, :"2.0", :symbol, :array, :literal]
p %i(ruby 2.0 symbol array literal)
#=> [:ruby, :"2.0", :symbol, :array, :literal]
@cielavenir
cielavenir / gist:3947132
Created October 24, 2012 16:27
Project Euler 94
#!/usr/bin/ruby
require 'enumerable/lazy' if RUBY_VERSION<'2.0'
a,b=2,1;p (0..1/0.0).lazy.map{a,b=a*2+b*3,a+b*2;s=2*(a%3==1?a+1:a-1)}.take_while{|s|s<=10**9}.reduce(:+)
@sandys
sandys / table_to_csv.rb
Created October 18, 2012 10:04
convert a html table to CSV using ruby
# run using ```rvm jruby-1.6.7 do jruby "-J-Xmx2000m" "--1.9" tej.rb```
require 'rubygems'
require 'nokogiri'
require 'csv'
f = File.open("/tmp/preview.html")
doc = Nokogiri::HTML(f)
csv = CSV.open("/tmp/output.csv", 'w',{:col_sep => ",", :quote_char => '\'', :force_quotes => true})
@gavinheavyside
gavinheavyside / fizzbuzz.rb
Last active September 27, 2019 08:43 — forked from mrb/fizzbuzz.rb
Writing FizzBuzz without modulus division or 'if'
fizz = [nil, nil, "Fizz"].cycle
buzz = [nil, nil, nil, nil, "Buzz"].cycle
(1..100).zip(fizz, buzz) do |num, *fb|
puts fb.compact.reduce(:+) || num
end