Ivor Horton
Ivor Horton

Reputation: 77

In Ruby, what does "new" mean in {1 => new("alice")}?

I'm new in Ruby and I mat the following code today. I've searched the "Ruby programming language" book but did not find explanation to this syntax. Could someone help to explain? I know to create an object you need to use something like Person.new("My name").

class Person
  attr_reader :name
  def initialize name
    @name = name
  end

  def self.find id
    people = {1 => new("alice"), 2 => new("bob")}
    people[id]
  end
end

Upvotes: 3

Views: 83

Answers (1)

falsetru
falsetru

Reputation: 369114

find is a class method.

In a class method, self refers the class. In a method, self can be omitted.

So, new means self.new; which is equivalent to Person.new in this case.

Upvotes: 6

Related Questions