1

I have a ruby class that has an Array as one of its instance variables. I'm trying to figure out how to validate data that is being pushed onto the array.

class Something
  def things
    @things ||= Array.new
  end
end

So I can declare an instance and add stuff to the array pretty easily this way.

@s = Something.new
@s.things << "one"
@s.things << "two"

I tried to create a class method named things<<(inString) to handle the validation but that is not valid syntax. So what approach can I take?

2 Answers 2

1

Try something like:

things << data if valid?(data)

where valid? is your validation method.

Example:

...
# will push only when quantity is greater than 0
def push(quantity)
  things << item if valid?(quantity)
end

private
  def valid?(number)
    number > 0
  end

If you want to have you own ThingsArray just create an Array subclass and override the push (<<) method to make the validation before pushing:

class ThingsArray < Array
  def << (item)
    return unless valid?(item)
    super
  end

  private

  def valid?(item)
    item > 0
  end
end

class Something
  def things
    @things ||= ThingsArray.new
  end
end 
Sign up to request clarification or add additional context in comments.

Comments

0

How about this?

class MyThings < Array
  def << (item)
    # do your validation with item
    self.push(item) if item.valid?
  end
end

class Something
  def things(item)
    @things ||= MyThings.new
  end
end

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.