Skip to content

Instantly share code, notes, and snippets.

@jnicklas
Created Feb 7, 2019
Embed
What would you like to do?
class Client
attr_reader :key,
def initialize(key)
@key = key
end
end
Client.new("moo") # results in: ArgumentError: wrong number of arguments (given 1, expected 0)
@jnicklas
Copy link
Author

jnicklas commented Feb 7, 2019

Can you figure it out? Expand for spoiler!

There is a trailing comma on the attr_reader. This causes the parser to see this as:

class Client
  attr_reader :key, (
    def initialize(key)
      @key = key
    end
  )
end

Since method definitions return their own name, this is effectively the same as:

class Client
  def initialize(key)
    @key = key
  end
  attr_reader :key, :initialize
end

So the initialize function gets overwritten with a reader for he @initialize instance variable.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment