Today I Learned

4 posts about #Ruby

Calling super method without arguments

It’s unusual that a mistake actually works in my favor. So, I was pleasantly surprised to see my tests passing when I forgot to pass the arguments from a child’s method implementation to the parent’s. Let’s look at an example.

class Parent
  def putz(*args)
    puts "calling puts from parent"
    puts(args)
  end
end

class Child < Parent
  def putz(*args)
    super
  end
end

Since no arguments are explicitly passed to the super call in the the child class’s putz method, Ruby will implicitly pass all the arguments received in the child method.

Child.new.putz('foo', 'bar', 'baz')
calling puts from parent
foo
bar
baz
=> nil

More information on how super behaves can be found here.

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