HolyMoly
HolyMoly

Reputation: 2080

methods attached to an end statement?

I am playing some coding challenges on codewars, after you pass a challenge you get to see other peoples answers, and one looks like this:

def weirdcase(string)
  string.split(' ').map do |word|
    word.split('').each_with_index.map do |char, i|
      i % 2 == 0 ? char.upcase : char.downcase
    end.join('')
  end.join(' ')
end

The code runs just fine. I have never seen a method attached to an end like this. I'm curious about it. I would love to know more about this such as: Is this common? Is it considered good or bad practice? Why would this be preferable in a situation, if it is? What are some examples of methods one may want to chain to an end?

Upvotes: 0

Views: 84

Answers (2)

neuronaut
neuronaut

Reputation: 2709

The method call isn't so much attached to the end keyword but rather to the result of the block that ends with the end keyword. Pretty much everything in Ruby returns a value, and pretty much every value is an object. As such, you can call methods on those values.

Upvotes: 2

user4426213
user4426213

Reputation:

This is called method chaining. It performs the chained method on the result of the previous method.

For instance this calls the .split method on the string variable which returns an array which the .map method is called on. string.split(' ').map do |word|

Upvotes: 2

Related Questions