Showing posts with label ways. Show all posts
Showing posts with label ways. Show all posts
Monday, April 11, 2011
Ways to map hashes
In Ruby, Hashes haven't the
However, sometimes we need to do something with the keys or the elements of a Hash. Here I show some ways to do that:
1. Through each_key or each_pair (first natural options, from reference):
2. Through merge (inspired here):
3. Here a way to modify the keys (from here):
4. A way to work with hashes sorted by keys (which I published here):
map or map! method; it's for Arrays.However, sometimes we need to do something with the keys or the elements of a Hash. Here I show some ways to do that:
1. Through each_key or each_pair (first natural options, from reference):
hash.each_key { |k| hash[k] = some_fun(hash[k]) }
hash.each { |k, v| hash[k] = some_fun(v) }
hash.each_pair { |k, v| hash[k] = some_fun(v) }
2. Through merge (inspired here):
hash.merge(hash) { |k, ov| sume_fun(ov) }
3. Here a way to modify the keys (from here):
Hash[*hash.map{|key,value| [key.upcase, value]}.flatten]
4. A way to work with hashes sorted by keys (which I published here):
hash.keys.sort.each { |k| puts k + " => " + hash[k] + "
\n" }
Sunday, April 3, 2011
Two ways to write an "increment" method
1. As I did in another post:
2. Inspired here:
inc = lambda do |x|
eval "#{x} += 1"
end
a = 5
inc[:a]
puts a #=> 6
2. Inspired here:
def inc(&blk)
eval "#{yield} += 1", blk
end
x = 5
inc {:x}
puts x #=> 6
Labels:
increment,
metaprogramming,
ruby,
ways
Tuesday, March 29, 2011
Two ways to simplify Array blocks in Ruby
1. If you have a block of the form
That works for other Array methods, like
2. If you have a block of the form
See more on it.
{ |v| v.mtd }:ary.each { |v| v.mtd } # normal way
ary.each(&:mtd) # simpler way
# Example:
ary = %w(abc def ghi jkl)
ary.each(&:upcase!) # same as ary.each { |v| v.upcase! }
That works for other Array methods, like
map. More on it.2. If you have a block of the form
{ |v| mtd v }, and the method mtd does the same thing with all parameters:ary.each { |v| mtd v } # normal way
mtd *ary # simpler way
#Example:
ary = %w(abc def ghi jkl)
puts *ary # same as ary.each { |v| puts v }
See more on it.
Subscribe to:
Posts (Atom)
