How to call method chaining using map method in ruby?

How can I call a block for use _id.to_s

in ruby?

category_ids = categories.map(&:_id.to_s)

      

I hack it and do the following:

category_ids = []
categories.each do |c|
  category_ids << c.id.to_s
end

      

+3


source to share


3 answers


You can pass a block to display and place your expression in a block. Each member of the enumerated will be passed sequentially to the block.



category_ids = categories.map {|c| c._id.to_s }

      

+8


source


category_ids = categories.map(&:_id).map(&:to_s)

      

Test:



categories = ["sdkfjs","sdkfjs","drue"]
categories.map(&:object_id).map(&:to_s)
=> ["9576480", "9576300", "9576260"]

      

+2


source


If you really want to bind methods, you can override the # to_proc symbol

* This answer is similar to the one voted. I wonder why...

class Symbol
  def to_proc
    to_s.to_proc
  end
end

class String
  def to_proc
    split("\.").to_proc
  end
end

class Array
  def to_proc
    proc{ |x| inject(x){ |a,y| a.send(y) } }
  end
end

strings_arr = ["AbcDef", "GhiJkl", "MnoPqr"]
strings_arr.map(&:"underscore.upcase")
#=> ["ABC_DEF", "GHI_JKL", "MNO_PQR"]

strings_arr.map(&"underscore.upcase")
#=> ["ABC_DEF", "GHI_JKL", "MNO_PQR"]

strings_arr.map(&["underscore", "upcase"])
#=> ["ABC_DEF", "GHI_JKL", "MNO_PQR"]

      

Ruby ampersand label

0


source







All Articles