Common Ruby Idioms

前端 未结 15 1973
星月不相逢
星月不相逢 2020-12-07 07:13

One thing I love about ruby is that mostly it is a very readable language (which is great for self-documenting code)

However, inspired by this question: Ruby Code ex

15条回答
  •  伪装坚强ぢ
    2020-12-07 07:32

    Nice question!

    As I think the more intuitive & faster the code is, a better software we’re building. I will show you how I express my thoughts using Ruby in little snippets of code. Read more here

    Map

    We can use map method in different ways:

    user_ids = users.map { |user| user.id }
    

    Or:

    user_ids = users.map(&:id)
    

    Sample

    We can use rand method:

    [1, 2, 3][rand(3)]
    

    Shuffle:

    [1, 2, 3].shuffle.first
    

    And the idiomatic, simple and easiest way... sample!

    [1, 2, 3].sample
    

    Double Pipe Equals / Memoization

    As you said in the description, we can use memoization:

    some_variable ||= 10
    puts some_variable # => 10
    
    some_variable ||= 99
    puts some_variable # => 10
    

    Static Method / Class Method

    I like to use class methods, I feel it is a really idiomatic way to create & use classes:

    GetSearchResult.call(params)
    

    Simple. Beautiful. Intuitive. What happens in the background?

    class GetSearchResult
      def self.call(params)
        new(params).call
      end
    
      def initialize(params)
        @params = params
      end
    
      def call
        # ... your code here ...
      end
    end
    

    For more info to write idiomatic Ruby code, read here

提交回复
热议问题