10

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
  • 66,169
  • 13
  • 144
  • 170
Kamilski81
  • 14,409
  • 33
  • 108
  • 161
  • 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

15

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,985
  • 3
  • 52
  • 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
  • 21,401
  • 12
  • 79
  • 130
  • If this is critical to performance, you can consider [Enumerator::Lazy](https://ruby-doc.org/3.2.2/Enumerator/Lazy.html) as [this comment in a related Q/A pointed out](https://stackoverflow.com/questions/76719614/how-do-you-efficiently-chain-array-methods-in-ruby?noredirect=1#comment135258089_76719614) – Cadoiz Jul 19 '23 at 11:17
4

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
  • 159
  • 1
  • 4