Today we’re asking Arrays to talk about everyones favorite subject: themselves.
#length || #size
An array never gets offended when you ask about its weight. In fact, you can ask in different ways:
musnts = ["listen", "to", "the", "musnt's", "child"] musnts.length => 5 musnts.size => 5
Of course, if it were empty, those would return 0.
#include?
You can get direct with Arrays about their souls and ask if they’re feeling they contain a specific item.
musnts = ["listen", "to", "the", "donts"] musnts.include?("musnts") => false musnts.include?(1) => false musnts.include?(true) => false musnts.include?("listen") => true
#count
One day, #size and #include? had a baby and named it #count. This is a third way to ask the same question as #length and #size, but it also takes an argument to do soul searching like #include? does.
musnts = ["listen", "to", "the", "shouldnts", "the", "impossibles", "the", "wonts"] musnts.count => 8 musnts.count("the") => 3 musnts.count("should") => 0 musnts.count(1) => 0 musnts.count(true) => 0
But, wait, folks, that’s not all. We can also pass it a block and put each of the array’s items under a grueling test of our choosing to determine if it meets our criteria. For this act, we will determine if the string in question has an “e” in it by calling String’s #include? method.
musnts = ["listen", "to", "the", "never", "haves"] musnts.count { |musnt| musnt.include?("e") } => 4
Four of the words contain the letter “e” (“listen”, “the”, “never”, “haves”). #count verified this by putting each item in this array under the microscope of #include?, which outputs either true or false for every item. Sadly, “to” generated a false, so he does not…count.
#empty?
If you didn’t know already, any method that ends in a “?” will return a boolean (true or false). We can ask an array if it feels empty inside for what is effectively a “yes” or “no” response.
musnts = ["then", "listen", "close", "to", "me"] musnts.empty? => false
Let’s reset the “musnts” variable to an empty array and try again.
musnts = [] musnts.empty? => true
Sorry to rip out your soul little “musn’ts”.
Today’s lorem ipsum is brought to us by the late Shel Silverstein and his poem, “LISTEN TO THE MUSTN’TS”
Listen to the MUSTN’TS, child,
Listen to the DON’TS
Listen to the SHOULDN’TS
The IMPOSSIBLES, the WONT’S
Listen to the NEVER HAVES
Then listen close to me-
Anything can happen, child,
ANYTHING can be