Ruby One-Liners

This is just a collection of quick Ruby tips.

1. Convert array to hash

[[:key, :value]].to_h

or

Hash[[["name","Nick"],["job","coder"]]]  

2. Swap hash keys and values

{ a: :b }.map { |k,v| [v,k] }.to_h

3. Generate a random alphanumeric password

(0...8).map { rand(33..125).chr }.join

4. Map-Reduce

BankAccount.all.map(&:balance).reduce(&:+)  

5. Show ActiveRecord queries in console in Rails 2.3

ActiveRecord::Base.connection.instance_variable_set :@logger, Logger.new(STDOUT)  

6. Format BSB numbers

'000333'.to_s.gsub(' ', '').gsub(/(.{3})(?=.)/, '\1 \2')  
# 000 333