Amidabrian Amidabrian - 21 days ago 4
Ruby Question

Select elements from an array starting with a certain character

I want select all the elements of this array that begin with a. Here is my code

a = ['bananas', 'apples', 'pears', 'avocados']
def select_elements_starting_with_a(a)
a.select { |str| str.start_with?('a') }
end
puts select_elements_starting_with_a


The error I am getting is

Untitled.rb:3:in `select_elements_starting_with_a': wrong number of arguments (0 for 1) (ArgumentError)
from Untitled.rb:6:in `<main>'

Answer

@Ursus and @Adam are right. But there is another point I'd like to make.

When you are programming, the way you name things sometimes show how clear is the definition of the problem in you mind. You've made this small confusion probably because a takes many roles in your code: a is the name of the array with the names of the fruits; a is also the name of the formal parameter used by your method.

Besides, this method is very specific. Too specific to be good, I must tell you. Assume your program should later identify all elements starting with letter b. I'd have to create another method, with almost the same code.

My suggestion, to make your code really reusable redefining the method as

def select_elements_starting_with(arr,letter)
  arr.select { |str| str.start_with?(letter) }
end

Now you may find elements starting with ANY letter in ANY array, and you won't risk forgeting to pass the paramenter because you'll make no confusion between the formal parameter and the real array instance being processed.

Comments