Today I Learned

2 posts about #Ruby

Installing the pg gem with the Postgres app

Everytime I need to install the pg gem to use Postgres with Rails I see the following error, and everytime I forget the solution.

An error occurred while installing pg (1.1.3), and Bundler cannot continue.
Make sure that gem install pg -v '1.1.3' --source 'https://rubygems.org/' succeeds before bundling.

Well, hey there, future self. Nice to see you. I think this is what you’re looking for.

gem install pg -- --with-pg-config=/Applications/Postgres.app/Contents/Versions/latest/bin/pg_config

Named arguments in Ruby

Using Ruby’s keyword arguments you can avoid the pitfalls of positional arguments as well as the extra code needed to extract values from a hash.

def total(subtotal:, tax:, discount:)
    subtotal + tax - discount
end

Default values can be provided if a named argument is not given to a method call.

def total(subtotal: 0, tax: 0, discount: 0)
  subtotal + tax - discount
end