Skip to content

Instantly share code, notes, and snippets.

@mungruby
mungruby / liddle_lizzard.rb
Created October 5, 2012 02:49
LiddleLizzard - a digital organism
class LiddleLizzard
CHROMOSOME_LENGTH = 500
include Comparable
attr_accessor :chromosome
def initialize
@chromosome = BitString.new(CHROMOSOME_LENGTH).bit_string
@mungruby
mungruby / random_strings.rb
Created October 2, 2012 03:58
Generate ascii strings
#!/usr/bin/env ruby -w
class BitString
attr_accessor :bit_string
def initialize string_length
@bit_string = random_bit_string string_length
end
@mungruby
mungruby / 0004_module.rb
Created June 4, 2012 03:04
Stacking Modules and super()
module TopLevel
module Greeter
module Person
def greeting
"Hello from #{name}. I am a #{age} year old #{gender}."
end
end
end
@mungruby
mungruby / singleton_struct.rb
Created May 29, 2012 02:10
Avoiding redefining constant Struct::ClassName warnings
fields = [:switch, :sha_ind, :dtdm, :utdm, :ttdm, :actual]
def create_struct name, fields
Struct.new(name, *fields)
end
def create_singleton_struct name, fields
if Struct::const_defined? name
Struct.const_get name
else
@mungruby
mungruby / nested_hash_example.rb
Created May 22, 2012 07:36
Nested Hash with Database
module MockRetriever
def self.fetch_rows database, table
return ["#{rand(100)} Main St.", "#{rand(100)} Second Ave.", "#{rand(100)} Peach Ln."]
end
end
module AddressHandler
# @addresses = Hash.new( {} ) # old code - returns the SAME hash, not a new hash
@addresses = Hash.new { |hash, key| hash[key] = {} }
@mungruby
mungruby / find_a_person.rb
Created May 19, 2012 03:24
example of using the inject method
#!/usr/bin/env ruby -w
# chmod +x inject_0001.rb
sclass = Struct.new('Person', :name, :age, :gender)
people = []
people << sclass.new("Sue", 20, 'M')
people << sclass.new("Sue", 20, 'F')
people << sclass.new("Sue", 21, 'M')
people << sclass.new("Joe", 20, 'M')
module InitialState
def self.state
:unborn
end
end
module Baby
def self.state
:feed_me
end
@mungruby
mungruby / 005_Struct.rb
Created May 1, 2012 20:42
Including a Module in a Struct
module Greeter
def greet
puts "Hello #{name}! You're a #{party}."
end
end
members = %w[name party]
customer = Struct.new('Customer', *members) do
include Greeter
@mungruby
mungruby / 003_Struct.rb
Created April 28, 2012 02:08
Add a method to a Struct
members = %w[NAME ADDRESS]
members.map!(&:downcase)
members.map!(&:to_sym)
Customer = Struct.new(*members) do
def print
puts self.to_a.join(",")
end
end
@mungruby
mungruby / var_args.rb
Created April 21, 2012 01:51
Variable Argument Lists
class VariableArguments
def initialize *args
@first, @second, @third = *args
end
end
v = VariableArguments.new
puts v.inspect
v = VariableArguments.new("Fred")