Monday, April 26, 2010

Ruby: Hash to Class

How to convert hash to class, to easily use it on views (i.e. in widgets, etc.)? Here's my solution:
class MacHash
  attr_accessor :hash

  def initialize hash
    self.hash = hash.symbolize_keys
  end

  def method_missing(method, *args)
    new_hash = hash[method]
    new_hash.is_a?(Hash) ? MacHash.new(new_hash) : new_hash
  end
end
And now we can test it:
hc = HashClass.new({:a => {:b => 10}, :c => [1, 2, 3]})

hc.a.b
=> 10

hc.c
=> [1, 2, 3]

Tuesday, December 22, 2009

Lotto (Duży Lotek) generator in Ruby

numbers = []
while(numbers.size != 6) do
 x = (rand(49) + 1)
 numbers << x unless numbers.include?(x)
end
numbers.sort!

Simple password generator in Ruby

The code is so simple that it needs no description:
(100000000000 + rand * 1000000000000).to_i.to_s(36)