9

How would I invoke the block to use _id.to_s in ruby?

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

I am hacking it and doing the following right now:

category_ids = []
categories.each do |c|
  category_ids << c.id.to_s
end
tokland
  • 63,578
  • 13
  • 136
  • 167
Kamilski81
  • 13,491
  • 31
  • 102
  • 150
  • 1
    The documentation for [`Enumerable#map`](http://ruby-doc.org/core-1.9.3/Enumerable.html#method-i-map) shows how to use a block. Did you look at it? – the Tin Man Feb 04 '13 at 16:15

3 Answers3

13

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 }
Winfield
  • 18,595
  • 3
  • 50
  • 65
7
category_ids = categories.map(&:_id).map(&:to_s)

Test:

categories = ["sdkfjs","sdkfjs","drue"]
categories.map(&:object_id).map(&:to_s)
=> ["9576480", "9576300", "9576260"]
megas
  • 20,851
  • 11
  • 74
  • 129
2

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

jmjm
  • 139
  • 1
  • 4