Ruby Using the "&:Methodname" Shortcut from Array.Map(&:Methodname) for Hash Key Strings Rather Than Methodname

ruby using the &:methodname shortcut from array.map(&:methodname) for hash key strings rather than methodname

You can do this with a lambda:

extract_keyname = ->(h) { h[:keyname] }
ary_of_hashes.map(&extract_keyname)

This tends to be more useful if the block's logic is more complicated than simply extracting a value from a Hash. Also, attaching names to your bits of logic can help clarify what a chain of Enumerable method calls is trying to do.

You can also have a lambda which returns a lambda if you're doing this multiple times:

extract = ->(k) { ->(h) { h[k] } }
ary_of_hashes.map(&extract[:keyname])
ary_of_hashes.map(&extract[:other_key])

or a lambda building method:

def extract(k)
->(h) { h[k] }
end

ary_of_hashes.map(&extract(:keyname))
ary_of_hashes.map(&extract(:other_key))

Can you use Ruby's block shorthand to call a method like the array accessor?

you can use Proc:

> a = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14]]
> third_elem = Proc.new {|x| x[2]}
> a.map(&third_elem)
#> [3, 7, 11, nil]

OR

> a.map &->(s) {s[2]}
#=> [3, 7, 11, nil]

all? method behavior with ampersand (&) and a block

This 'ampersand' notation is a short form of:

coordinates.all? { |c| c.valid_coordinate? }

It's obviously different from what you wanted since valid_coordinate? is being called on the object held by c variable instead of self:

coordinated.all? { |c| valid_coordinate?(c) }

And that's why it doesn't work.

possible to do this as a one-liner in Ruby or Rails

You're almost there. Try this:

ad_source_ids = logged_one['migrated'].collect { |mig| mig['id'] }

Group array of hashes by value and retain structure (hash) in Ruby

This should work:

hash.group_by { |k,v| v[:where] }.each { |_, v| v.map! { |array| { array[0] => array[1] } } }

Or with transform_values

hash.group_by { |k,v| v[:where] }.transform_values { |v| v.map { |array| {array[0] => array[1] } } }

https://ruby-doc.org/core-2.4.0/Hash.html#method-i-transform_values

Sorting/accessing through an array of nested hashes

Since your Array array consists of Hashes, when you do array.first a Hash is returned {"bill" => 12}.

You can now define a method Hash#name that can be applied to array.first
(a Hash)

Here:

class Hash
def name
self.keys.first
end
end

array.first.name
# => "bill"

#to print all names
array.each{|a| puts a.name}
# bill
# tom
# pat

# or collect them in an Array
array.map(&:name)
# => ["bill", "tom", "pat"]


Related Topics



Leave a reply



Submit