Ruby-Example

One way to learn new Ruby tricks, patterns & methods is to read code others have written.

We have many open source projects, and coding challenge sites that allow you to see the solutions from other developers once you submit your own.

for i in (1..10)
    rno = rand(100) + 1
    msg = case rno
        when 42: "The ultimate result."
        when 1..10: "Way too small."
        when 11..15,19,27: "Sorry, too small"
        when 80..99: "Way to large"
        when 100:
                print "TOPS\n"
                "Really way too large"
        else "Just wrong"
    end
    print "Result: ", rno, ": ", msg, "\n"
end

Admittedly, his code doesn’t look very useful. However, immediately-invoked method can be more valuable in other ways.

You might know that method definition returns method name as a symbol, and it means that we can use it like this:  

So, basically every method that accepts the method name as an argument can be rewritten as

class RailsController 
  helper_method def current_user
    User.current
  end
end

Autor

Kaspar Lüthi
Kaspar Lüthi
Kaspar has spent over a decade helping thousands of businesses worldwide to build publicity and market themselves more effectively.

He's the founder of vWriter, a powerful content marketing platform for businesses and agencies, helping them create and distribute content across multiple high-traffic content platforms, including social media.
Letzte Beiträge