Home > Net >  Take an array of words, return the array of words not exceeding max_length characters (reject)
Take an array of words, return the array of words not exceeding max_length characters (reject)

Time:10-30

I working on a exercise, i need to use .reject to sort some item on a array.

here is the code i'm traying:

def short_words(array, max_length)
  array.reject { |words, value| words if value > max_length }
end

**# TODO: Take an array of words, return the array of words not exceeding max_length characters **# You should use Enumerable#reject

CodePudding user response:

The array is a list of words. The reject methods takes these words one by one and decides which ones to ehm... reject. So in the block it is much clearer to refer to them as |word|. To determine the amount of characters strings happen to have a size method (word.size). value is completely unnecessary.

CodePudding user response:

Simply use .size on each string in the array and compare it against you max_length

array = %w(spain france ireland uk bosnia portugal)
array.reject { |term| term.size > 5 }
=> ["spain", "uk"]
  • Related