How do i invoke a method chain using map method, in ruby?

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

Test:

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

You can pass a block to map and put your expression within the block. Each member of the enumerable will be yielded in succession to the block.

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

If you really want to chain methods, you can override the Symbol#to_proc

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"]

category_ids = categories.map(&"id.to_s")

Ruby ampersand colon shortcut

IRB

Tags:

Ruby