Common Ruby Idioms

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

    Some more idioms:

    Use of the %w, %r and %( delimiters

    %w{ An array of strings %}
    %r{ ^http:// }
    %{ I don't care if the string has 'single' or "double" strings }
    

    Type comparison in case statements

    def something(x)
      case x
        when Array
          # Do something with array
        when String
          # Do something with string
        else
          # You should really teach your objects how to 'quack', don't you?
      end
    end
    

    ... and overall abuse of the === method in case statements

    case x
      when 'something concrete' then ...
      when SomeClass then ...
      when /matches this/ then ...
      when (10...20) then ...
      when some_condition >= some_value then ...
      else ...
    end
    

    Something that should look natural to Rubyists, but maybe not so to people coming from other languages: the use of each in favor of for .. in

    some_iterable_object.each{|item| ... }
    

    In Ruby 1.9+, Rails, or by patching the Symbol#to_proc method, this is becoming an increasingly popular idiom:

    strings.map(&:upcase)
    

    Conditional method/constant definition

    SOME_CONSTANT = "value" unless defined?(SOME_CONSTANT)
    

    Query methods and destructive (bang) methods

    def is_awesome?
      # Return some state of the object, usually a boolean
    end
    
    def make_awesome!
      # Modify the state of the object
    end
    

    Implicit splat parameters

    [[1, 2], [3, 4], [5, 6]].each{ |first, second| puts "(#{first}, #{second})" }
    

提交回复
热议问题