Hidden features of Ruby

Continuing the "Hidden features of ..." meme, let's share the lesser-known but useful features of Ruby programming language.

Try to limit this discussion with core Ruby, without any Ruby on Rails stuff.

See also:

  • Hidden features of C#
  • Hidden features of Java
  • Hidden features of JavaScript
  • Hidden features of Ruby on Rails
  • Hidden features of Python
  • (Please, just one hidden feature per answer.)

    Thank you


    从Ruby 1.9 Proc#===是Proc#调用的别名,这意味着Proc对象可以在case语句中使用,如下所示:

    def multiple_of(factor)
      Proc.new{|product| product.modulo(factor).zero?}
    end
    
    case number
      when multiple_of(3)
        puts "Multiple of 3"
      when multiple_of(7)
        puts "Multiple of 7"
    end
    

    Peter Cooper has a good list of Ruby tricks. Perhaps my favorite of his is allowing both single items and collections to be enumerated. (That is, treat a non-collection object as a collection containing just that object.) It looks like this:

    [*items].each do |item|
      # ...
    end
    

    不知道这是如何隐藏的,但是我发现它需要在一维数组中生成一个Hash:

    fruit = ["apple","red","banana","yellow"]
    => ["apple", "red", "banana", "yellow"]
    
    Hash[*fruit]    
    => {"apple"=>"red", "banana"=>"yellow"}
    
    链接地址: http://www.djcxy.com/p/42808.html

    上一篇: WPF和XAML的隐藏功能?

    下一篇: Ruby的隐藏功能