Is it possible to use map(&:func)
with object, such as in array.map(&:func).with_object(object)
instead of array.map { |element| element.func(object) }
?
Asked
Active
Viewed 4,277 times
4

sawa
- 165,429
- 45
- 277
- 381

Vyacheslav Shved
- 41
- 1
- 3
-
1It sounds like you're trying to pass an argument with the method when using the map shorthand syntax. If so, this might help: [http://stackoverflow.com/questions/23695653/can-you-supply-arguments-to-the-mapmethod-syntax-in-ruby] – dwenzel Oct 11 '15 at 21:36
-
@dwenzel, Thx a lot! It hink, it is exactly what I need – Vyacheslav Shved Oct 11 '15 at 21:42
-
Try this: `array.map.with_object(object, &func)`. Be aware that using existing object methods (signified by the `:` shorthand), as in: `array.map.with_object(object, &:to_s)` will usually be meaningless when using the `with_object`. – Myst Oct 11 '15 at 21:44
-
@Myst, `array.map.with_object(object, &func)` doesn't work, it returns object as result. – Vyacheslav Shved Oct 11 '15 at 21:49
-
@dwenzel, in question I hoped I shouldn't redefine or define some methods. Furthermore I think that once I wrote something like that, but it is possible with the use of the `.reduce` method – Vyacheslav Shved Oct 11 '15 at 21:55
-
This is because using both `map` and `with_object` doesn't do what you expect - these two conflict in a way. `map` returns an enumerator. When a block is passed, the returned value is an array containing all of the block's returned values. The `with_object` modifies the Enumerator so that the object is passed along to the block with each iteration and the returned value is the object (modified or not by the block). using `array.each.with_object(object, &block)` makes more sense. – Myst Oct 11 '15 at 22:41