ruby -rubygems

You know, I’ve always wondered why requiring a library on the command line is ruby -r library but you can require rubygems with ruby -rubygems. Here’s why:

[rubygems-1.3.5] cat lib/ubygems.rb 
# This file allows for the running of rubygems with a nice
# command line look-and-feel: ruby -rubygems foo.rb
#--
# Copyright 2006 by Chad Fowler, Rich Kilmer, Jim Weirich and others.
# All rights reserved.
# See LICENSE.txt for permissions.
#++


require 'rubygems'

Nice hack.

Madoff Typing

# We have invented a new kind of duck-typing, we call it Madoff typing.
# We just lie and hope we die before you recognize our scheme. :)

Chef’s attribute.rb

Shadow Passwords in Ruby

Want to generate a shadow password (that you can put in /etc/shadow) in Ruby?

POSSIBLE = [('a'..'z'),('A'..'Z'),(0..9),'.','/'].inject([]) {|s,r| s+Array(r)}

def shadow(password)
  salt = Array.new(8) { POSSIBLE[ rand(POSSIBLE.size) ] }
  password.crypt("$1$#{salt}")
end

My version of this. As per the comment there, if you aren’t getting a result that looks like “$1$somesalt$biglonghash”, you need glibc2.

Fixnum#to_bit_array

We just spent far too long trying to figure out how to use #unpack or #pack in some combination to convert a Fixnum (Integer) into an array of its bits. Turns out, Google provides a far superior solution:

bits = Array.new(8) { |i| 7[i] }.reverse!

Apparently Fixnum#[] returns the n-th bit. Who knew?

Return with Splat in Ruby 1.9

This looks like a bug to me…(‘cept I’m sure it’s not)

$ cat splats.rb 
def splat1
  rv = [nil]
  return *rv
end

def splat2
  rv = [nil,nil]
  return *rv
end

foo = splat1
bar, baz = splat2

puts foo.inspect
puts bar.inspect
puts baz.inspect

$ ruby -v
ruby 1.8.7 (2009-04-08 patchlevel 160) [i686-darwin9.6.0]
$ ruby splats.rb 
nil
nil
nil

$ ruby -v
ruby 1.9.1p129 (2009-05-12 revision 23412) [i386-darwin9.7.0]
$ ruby splats.rb 
[nil]
nil
nil

(Notice the difference when returning the splatted array [nil].)

EDIT: I forgot to check the ‘question’ box on Tumblr, but if you know what’s going on here, please get it touch.

http_require

Wouldn’t it be cool if you could just require “http://my-host/my-lib.rb” in ruby?

No, because that would be evil.

Now You Can! Using our “http_require” gem! :-)

That’s it, I’m moving to Python.