i make beer, music, and code. sometimes in that order. @aberant on twitter
Comments
Comments
Comments

ruby drive-by: autovivification

need multi-level hashes in a hurry? (assumes 1.9)

h = Hash.new {|h,k| h[k] = Hash.new(&h.default_proc)}
h["foo"]["bar"]["baz"] = 42
h["foo"] #=> {"bar"=>{"baz"=>42}} 
Comments

ruby’s dusty corners: -n

if you are a perl hacker, then what this does is probably no surprise to you.  if you specify “-n” as an argument to ruby, then it wraps your code in a ‘while gets() … end’ loop.

lets pretend grep didn’t exist and i wanted a bit of code to loop through all my ruby files and print the lines where i was using the RUBYLIB constant.  i would create something like this.

ruby -ne “print if /RUBYLIB/” *.rb

note that there is a print and not a puts in that code.  IO#print with no arguments prints $_ which is the last line fetched by a gets or readline.    

Comments
Comments
Comments
Comments
Comments
Comments