什么是简短、简单、有用、酷、令人印象深刻或极客的Ruby代码?

什么是简短、简单、有用、酷、令人印象深刻或极客的Ruby代码?,ruby,Ruby,比如, @second = 2 @foo = @first || @second || @third p @foo #=> 2 及 我期待着阅读一个有趣的代码! 谢谢:) (编辑)以下是更详细的版本: class Array def to_hash keys_and_values = self.map {|x| [x, yield(x)] } # Now `keys_and_values` is an array of arrays reperesenting

比如,

@second = 2
@foo = @first || @second || @third
p @foo #=> 2

我期待着阅读一个有趣的代码! 谢谢:)

(编辑)以下是更详细的版本:

class Array
  def to_hash
    keys_and_values = self.map {|x| [x, yield(x)] }
    # Now `keys_and_values` is an array of arrays reperesenting
    # the hash. If the array this method was called on was, for
    # example, `[1, 2, 3]`, and the block passed to this method
    # was `{|x| x + 1 }`, `keys_and_values` would be:
    #
    #     [[1, 2], [2, 3], [3, 4]]


    keys_and_values = keys_and_values.flatten
    # now `keys_and_values` still contains all of the keys/values
    # of the new hash, but without the inner arrays. Even numbered
    # indexes will be keys, and odd indexes will be values. Example:
    #
    #     [1, 2, 2, 3, 3, 4]


    Hash[*keys_and_values]
    # This returns the keys/values translated to a hash. The docs
    # for the `Hash.[]` method is here:
    #
    #     http://ruby-doc.org/core/classes/Hash.html#M002839
  end
end

使用正则表达式检查整数
n
是否为素数的函数

def is_prime(n)
    ("1" * n) !~ /^1?$|^(11+?)\1+$/
end

说明和来源。

使用enum.zip和block:

class Array
  def to_hash(&b)
    Hash[*self.zip([b.call]*self.size).flatten]
  end
end
#[1,2,3].to_hash{'n'} >> {1=>'n',2=>'n',3=>'n'}

读一下解释。我得再投一次。哇,它又强大又漂亮!谢谢你的推荐,它比ruby还老。我很确定这个正则表达式在90年代的某个时候首次出现在comp.lang.perl.misc newgroup中Abigail的一个SIG中。很高兴你们喜欢它。。。如果你打算用它来处理素数,请记住Ruby内置了一个素数生成器。这里有一篇文章介绍了它在现实生活中的应用:哇,它看起来非常古怪!对不起,我不能理解这个代码。发生什么事?如果可能的话,我想读一段很长的代码。我试着用下面的代码。这个用法好吗?[“abc”,“def”,“ghi”]谢谢。@bekkou68:请看我的编辑,它解释了这一点。这不是主观的定义吗。至少应该是CW
def is_prime(n)
    ("1" * n) !~ /^1?$|^(11+?)\1+$/
end
class Array
  def to_hash(&b)
    Hash[*self.zip([b.call]*self.size).flatten]
  end
end
#[1,2,3].to_hash{'n'} >> {1=>'n',2=>'n',3=>'n'}