Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

About this user

Jake Varghese http://www.djdossiers.com

« Newer Snippets
Older Snippets »
Showing 1-2 of 2 total  RSS 

Float to_s hack for easy sprintf'ing

Float Hacks:
1. to_s override.
I really hate using sprintf, mainly because i always have to go online
and look up the syntax. I figured i could make that a little easier.
Now you can print floats with different precision as easily as:

4.123456.to_s(1) # => "4.1"
4.123456.to_s(3) # => "4.12"
4.123456.to_s(3) # => "4.123"
4.123456.to_s(4) # => "4.1235" (Note the auto rounding from 4.123456)
4.123456.to_s # => "4.123456"


class Float
  alias_method :orig_to_s, :to_s
  def to_s(arg = nil)
    if arg.nil?
      orig_to_s
    else
      sprintf("%.#{arg}f", self)
    end
  end
end


I have packaged this and other useful hacks into a plugin at http://blog.djdossiers.com/articles/2007/03/31/new-rails-plugin-jakes-toolbox

Peace

--jake

Hash Referencing Hack for Ruby

Hash Hacks:
1. Method Missing hack to allow easy referencing.
I can never remember whether the Hash i am playing with has symbols for keys or
strings. I also dont like typing the brackets (not all text editors have the
cool "close brace" feature). That's why i came up with this method missing hack.
Instead of explaining what it does, I'll just show you.

Example:
hsh = {"project"=>
{ "prototype_url"=>nil,
"designer_id"=>2,
"finished_at"=>nil, "phone_number"=>"512225555",
"website"=>"http://www.ggg.com",
"first_name"=>"test",
}
}
hsh.project
#=> {"prototype_url"=>nil, "designer_id"=>2, "finished_at"=>nil, "phone_number"=>"512225555", "website"=>"http://www.ggg.com", "first_name"=>"test"}

hsh.project.prototype_url #=> nil
hsh.project.designer_id #=> 2
hsh.project.first_name #=> test

class Hash    		
  def method_missing(method_id, *args, &block)
    method_name = method_id.to_s
    check = self.stringify_keys
    if check.keys.include?(method_name)
      check[method_name]
    else
      super
    end
  end
end




I have packaged this and other useful hacks into a plugin at http://blog.djdossiers.com/articles/2007/03/31/new-rails-plugin-jakes-toolbox

Peace

--jake
« Newer Snippets
Older Snippets »
Showing 1-2 of 2 total  RSS