Boolean methods in Ruby?

To ask something like:

MyClass::create().empty?

How do I configure emptyin MyClass?

Empty (true / false) depends on whether the class variable is empty @arror not.

+5
source share
4 answers

The question icon is actually part of the method name, so you should do the following:

class MyClass

  def empty?
    @arr.empty? # Implicitly returned.
  end

end
+7
source

In exactly the same way as I showed in the last post, but with a different method name.

First, it createshould return something using the method empty?. For instance:

class MyClass
  def self.create
    []
  end
end

If you want to work with instances MyClassaccording to your last question:

class MyClass
  def self.create
    MyClass.new
  end

  def initialize
    @arr = []
  end

  def empty?
    @arr.empty?
  end

  def add x
    @arr << x
    self
  end
end

It MyClassacts like a simple wrapper around an array, providing a method add.

pry(main)> MyClass.create.empty?
=> true
+2

, @arr . .

def empty?
  !@arr || @arr.empty?
end
+2

Forwardable empty? :

require "forwardable"
class MyClass
  extend Forwardable
  def_delegators :@arr, :empty?

  def initialize(arr)
    @arr = arr
  end
end

my_object = MyClass.new([])
my_object.empty? # => true
0
source

All Articles