a = [1, 2, 3] Hash[*a.collect { |v| [v, v*2] }.flatten]
It's not as foolproof as his solution, however!
11391 users tagging and storing useful source code snippets
Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world
a = [1, 2, 3] Hash[*a.collect { |v| [v, v*2] }.flatten]
class Array
def to_h(&block)
Hash[*self.collect { |v|
[v, block.call(v)]
}.flatten]
end
end
class Array def to_hash_keys(&block) Hash[*self.collect { |v| [v, block.call(v)] }.flatten] end def to_hash_values(&block) Hash[*self.collect { |v| [block.call(v), v] }.flatten] end end
>> a = ["able", "baker", "charlie"] >> a.to_hash_values {|v| a.index(v)} => {0=>"able", 1=>"baker", 2=>"charlie"}
>> id_list = (21..31).to_a => [21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31] >> products_ids = [24, 29, 30, 32] => [24, 29, 30, 32] >> results = Hash[*id_list.collect {|v| [v, products_ids.include?(v)]}.flatten] => {27=>false, 22=>false, 28=>false, 23=>false, 29=>true, 24=>true, 30=>true, 25=>false, 31=>false, 26=>false, 21=>false} >> results.each_pair {|k,v| puts "Key: #{k} is true!" if v == true} Key: 29 is true! Key: 24 is true! Key: 30 is true!
class << Hash def create(keys, values) self[*keys.zip(values).flatten] end end
>> Hash.create(['a', 'b', 'c'], [1, 2, 3]) => {"a"=>1, "b"=>2, "c"=>3}
class Array def flatten_once returning([]) {|ary| each{|x| ary.concat x}} end end
class Array def flatten_once inject([]) { |v, e| v.concat(e)} end end
You need to create an account or log in to post comments to this site.