0

I'm up against something I don't quite understand.

Here's the class I've created, and the driver code I'm running to test my method:

class Dog < Array
  def breathing?
    self.length > 1
  end
end

the_dog = Dog.new(["Arf", "Woof"])

puts the_dog.breathing?
# true

the_dog.shift

puts the_dog.breathing?
# false

How come, when I call #shift on the_dog, the_dog stops breathing?

4
  • 3
    Because the_dog.length isn't greater than 1. Did you want to use>=? Also, inheriting from core classes might not go well (sadly), use instance variables. Commented Jul 10, 2015 at 18:02
  • Especially inheriting from Array is bad. I have yet to see a use case where it'd be warranted. Commented Jul 10, 2015 at 18:06
  • 2
    Also, what's up with this array dog? Commented Jul 10, 2015 at 18:07
  • I think it's disrespectful to name man's best friend, "the_dog". Commented Jul 11, 2015 at 4:36

1 Answer 1

1

Shift method returns the first element of self and removes it (shifting all other elements down by one). Returns nil if the array is empty.

a = [1,2,3]
a.shift
=> [2,3]

So, In your case the first argument of the array is removed. Once its removed, the condition the_dog.breathing? is returned false.

Sign up to request clarification or add additional context in comments.

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.