Bart_Judge
Bart_Judge

Reputation: 97

The Well Grounded Rubyist - Syntax Question - Optional Argument or Hash Argument

I'm currently going through "The Well Grounded Rubyist 2nd Edition" I'm on page 296 and have been given the following code

class Person
  attr_accessor :age

  def initialize(options)
    self.age = options[:age]
  end

  def teenager?
    (13..19) === age
  end
end

what does options[:age] refer to? is it an optional argument or something? If I were writing that class, I would have written that line like @age = options

Edit - I forgot to mention, I did find this question - Rails optional argument - that uses the line used in the book. But i couldn't work out why it was used or why options was used with the symbol [:age].

Upvotes: 0

Views: 48

Answers (1)

Sebastián Palma
Sebastián Palma

Reputation: 33471

options isn't an optional argument, because initializing a Person object without that argument would throw an ArgumentError error, because it's expecting one argument but you passed no argument:

Person.new
# file.rb:4:in `initialize': wrong number of arguments (given 0, expected 1) (ArgumentError)

In that case options is meant to be a hash or any object that responds to the method []. So, if you initialize a Person object with hash containing the symbol key age, then self.age will take that value:

p Person.new(age: 100)
# <Person:0x00007ff05b84eab0 @age=100>

The use of hash as arguments gives you a flexibility at the moment of invoking a method, because you can wrap any needed object into the hash, you just need to take care of handling them in the method definition.

If you do self.age = options (or @age = options), then you're assigning to self.age the whole options object, which can be the whole hash or anything passed as the argument:

def initialize(options)
  self.age = options
end
...

p Person.new(age: 100, another_thing: nil)
# #<Person:0x00007ff47e09aa18 @age={:age=>100, :another_thing=>nil}>

Upvotes: 2

Related Questions