antonpug
antonpug

Reputation: 14296

Boolean methods in Ruby?

In order to ask something like:

MyClass::create().empty?

How would I set up empty within MyClass?

Empty (true/false) depends on whether a class variable @arr is empty or not.

Upvotes: 5

Views: 7342

Answers (4)

Andrew Grimm
Andrew Grimm

Reputation: 81480

You could use Forwardable to delegate empty? from your class to the array:

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

Upvotes: 0

Daniel Le
Daniel Le

Reputation: 1830

You might also need to check whether @arr is nil or not. This depends on your class definition of empty.

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

Upvotes: 2

Dave Newton
Dave Newton

Reputation: 160181

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

First, create must return something with an empty? method. For example:

class MyClass
  def self.create
    []
  end
end

If you want to be operating on instances of MyClass as per 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

Here MyClass acts as a simple wrapper around an array, providing an add method.

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

Upvotes: 2

user142019
user142019

Reputation:

The question mark is actually part of the method name, so you would do this:

class MyClass

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

end

Upvotes: 7

Related Questions