Zach Smith Zach Smith - 5 months ago 8
Ruby Question

Ruby: How does method chaining with block iterators work?

The below code seems to work. I'm not sure why though... as far as I know the

.each_char
takes a code block as does the
select
method. So I'm new at all Ruby and apologize if this question has been asked before.

Here is the code:

def word_test(word)
vowels = ["a","e","i","o","u"]
word_vowels = Hash.new()

word_vowels = word.to_s.each_char.select {|char| vowels.include?(char)}
if word_vowels == word_vowels.sort
return true
end
end

word_test("hello")


How is it possible to append methods that require code blocks onto methods?

Answer

Have a look at the documentation for String#each_char. "Passes each character in str to the given block, or returns an enumerator if no block is given." This frase "or returns an enumerator if no block is given" appears frequently in Ruby doc's - it's what makes this "stacking methods on top of each other" useful. Actually it's called "method chaining".

Sidenote:

if word_vowels == word_vowels.sort
    return true
end

#better:

word_vowels == word_vowels.sort
Comments