How to create classes that can be instantiated without using new in Ruby

Asked 2 years ago, Updated 2 years ago, 35 views

How do I create classes that I can use without using new like Post.all like ActiveRecord?

For example, by defining something for a class called Person,

Person('yoshida').age

I'm thinking of using it in a way that I can.

Also, is there a name like this?Instanceless class.

ruby

2022-09-30 19:35

3 Answers

Create a class method instead of an instance method.

class Post
  def self.all
    [1,2,3]
  end
end

post.all


2022-09-30 19:35

Ruby can do this if you write something like Post['ruby'].name.
However, I believe that class design using method chains such as Post.find('ruby').name is more Ruby-like.

class Post
  attr_reader:name

  def initialize (name)
    @name = name
  end

  def self. [ ] (name )
    new(name)
  end
end

puts Post ["ruby"].name#=>ruby


2022-09-30 19:35

Although it is not クラスsome definition for a class に, you can define a method with the same name apart from the class.

class Person
    attr_accessor:name, :age
end

def Person (name)
    person = Person.new
    person.name = name
    person.age = 20
    person
end

pPerson('yoshida').age#=>20

If you want to define for a class (although the writing changes slightly), you can also define self.call.

class Person 2
    attr_accessor:name, :age
    def self.call(name)
        person = new
        person.name = name
        person.age = 30
        person
    end
end

# Need dot for call
pPerson2.('yoshida').age#=>30


2022-09-30 19:35

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.