Common Ruby Idioms

前端 未结 15 1896
星月不相逢
星月不相逢 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:29

    method missing magick

    class Dummy  
      def method_missing(m, *args, &block)  
        "You just called method with name #{m} and arguments- #{args}"  
      end  
    end
    
    Dummy.new.anything(10, 20)
    => "You just called method with name anything and arguments- [10, 20]"
    

    if you call methods that not exists in ruby objects, ruby interpreter will call method called 'method_missing' if its defined, you could user this for some tricks, like writing api wrappers, or dsl, where you don;t know all methods and parameters names

    0 讨论(0)
  • 2020-12-07 07:30

    You can deepcopy with Marshaling object easily. - taken from The Ruby Programming Language

    def deepcopy(o)
      Marshal.load(Marshal.dump(o))
    end
    

    Note that files and I/O streams, as well as Method and Binding objects, are too dynamic to be marshaled; there would be no reliable way to restore their state.

    0 讨论(0)
  • 2020-12-07 07:32

    By the way, from the referenced question

    a ||= b 
    

    is equivalent to

    if a == nil   
      a = b 
    end
    

    That's subtly incorrect, and is a source of bugs in newcomers' Ruby applications.

    Since both (and only) nil and false evaluate to a boolean false, a ||= b is actually (almost*) equivalent to:

    if a == nil || a == false
      a = b
    end
    

    Or, to rewrite it with another Ruby idiom:

    a = b unless a
    

    (*Since every statement has a value, these are not technically equivalent to a ||= b. But if you're not relying on the value of the statement, you won't see a difference.)

    0 讨论(0)
  • 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

    0 讨论(0)
  • 2020-12-07 07:36

    I like this:

    str = "Something evil this way comes!"
    regexp = /(\w[aeiou])/
    
    str[regexp, 1] # <- This
    

    Which is (roughly) equivalent to:

    str_match = str.match(regexp)
    str_match[1] unless str_match.nil?
    

    Or at least that's what I've used to replace such blocks.

    0 讨论(0)
  • 2020-12-07 07:37

    I like how If-then-elses or case-when could be shortened because they return a value:

    if test>0
      result = "positive"
    elsif test==0
      result = "zero"
    else
      result = "negative"
    end
    

    could be rewriten

    result = if test>0
      "positive"
    elsif test==0
      "zero"
    else
      "negative"
    end
    

    The same could be applied to case-when:

    result = case test
    when test>0 ; "positive"
    when test==0 ; "zero"
    else "negative"
    end
    
    0 讨论(0)
提交回复
热议问题