Common Ruby Idioms

前端 未结 15 1895
星月不相逢
星月不相逢 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})" }
    
    0 讨论(0)
  • 2020-12-07 07:20

    I always forget the exact syntax of this shorthand if else statement (and the name of the operator. comments anyone?) I think it's widely used outside of ruby, but in case someone else wants the syntax here it is:

    refactor < 3 ? puts("No need to refactor YET") : puts("You need to refactor this into a  method")
    

    expands to

    if refactor < 3
      puts("No need to refactor YET")
    else
      puts("You need to refactor this into a  method")
    end
    

    update

    called the ternary operator:

    return myvar ? myvar.size : 0

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

    Here's a few, culled from various sources:

    use "unless" and "until" instead of "if not" and "while not". Try not to use "unless" when an "else" condition exists, though.

    Remember you can assign multiple variables at once:

    a,b,c = 1,2,3
    

    and even swap variable without a temp:

    a,b = b,a
    

    Use trailing conditionals where appropriate, e.g.

    do_something_interesting unless want_to_be_bored?
    

    Be aware of a commonly-used but not instantly obvious (to me at least) way of defining class methods:

    class Animal
      class<<self
        def class_method
          puts "call me using Animal.class_method"
        end
      end
    end
    

    Some references:

    • http://cbcg.net/talks/rubyidioms/index.html
    • http://www.therailsway.com/2006/12/8/idiomatic-ruby
    • http://www.therailsway.com/2007/1/21/more-idiomatic-ruby
    • http://www.caliban.org/ruby/rubyguide.shtml
    0 讨论(0)
  • 2020-12-07 07:21
    a = (b && b.attribute) || "default"
    

    is roughly:

    if ( ! b.nil? && ! b == false) && ( ! b.attribute.nil? && ! b.attribute.false) a = b
    else a = "default"
    

    I use this when b is a record which may or may not have been found, and I need to get one of its attributes.

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

    Array.pack and String.unpack for working with binary files:

    # extracts four binary sint32s to four Integers in an Array
    data.unpack("iiii") 
    
    0 讨论(0)
  • 2020-12-07 07:25

    This slideshow is quite complete on the main Ruby idioms, as in:

    • Swap two values:

      x, y = y, x

    • Parameters that, if not specified, take on some default value

      def somemethod(x, y=nil)

    • Batches up extraneous parameters into an array

      def substitute(re, str, *rest)

    And so on...

    0 讨论(0)
提交回复
热议问题