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 :)
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 :)
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
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.
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'}