tags:

views:

155

answers:

3

For examples,

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

and

p [1, 2, 3].map(&:to_s) #=> ["1", "2", "3"]

I'm looking forward to reading an interesting code! Thanks :)

+1  A: 
class Array
  def to_hash; Hash[*map {|x| [x, yield(x)] }.flatten]; end
end

(Edit) Here is a more verbose version:

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
Adrian
Wow, it looks like very geeky! I'm sorry but I can't understand this code. What's going on? If possible, I'd like to read a lengthy code of this.And I tried to use this code with the following one. Is it nice usage? ["abc", "def", "ghi"].to_hash { |i| "same" } #=> {"abc"=>"same", "def"=>"same", "ghi"=>"same"}Thanks.
bekkou68
@bekkou68: See my edit, which explains it.
Adrian
+5  A: 

A function that checks if an integer n is prime using regex!

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

Explanation and source here.

maksim
Just read the explanation. I HAVE to upvote this one more time.
Eimantas
Wow, it's powerful and beautiful!And thanks for putting the reference.
bekkou68
It's also older than ruby. I'm pretty sure this regex first appeared in one of Abigail's sigs in the comp.lang.perl.misc newgroup sometime in the 90's.
Don Roby
Glad you folks liked it... if you are planning to use it to do work with prime numbers, keep in mind Ruby has a prime generator built in.
maksim
Here's an article on its use in real life settings: http://zmievski.org/2010/08/the-prime-that-wasnt
maksim
A: 

using enum.zip and 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'}
Abdelrahman