&

Hi
How can I call a proc with args ?
....map(&:myproc(n))
# => unexpected '('

And: How can I use & with a 'normal' method?

def ss(n)
  print n+1
end

....map(&:ss(n)) # or sg else, is there a shorter/better/working form
for/instead of:
....map { |x| x.ss(n) }

Thanks
Berg

Hi
How can I call a proc with args ?
....map(&:myproc(n))
# => unexpected '('

You don't call a proc with args. The `map` method here calls your proc,
in other words it yields to it. It controls what parameters are yielded.

The `&` in this case is actually called "symbol to proc".

And: How can I use & with a 'normal' method?

You can use `&method(:method_name)` like this:

     search = "Google;
     queries = ["symbol+to_proc", "rubytapas+callable", "UnboundMethod"]

     queries.map(&search.method(:+))

Just like `:symbol.to_proc`, You could write your own `method_to_proc` wrapper, it depends what you're trying to do.

You can also use anything that responds to `call` so you can build your
own object that gets initialized and called however you want.

Andrew Vit

···

On 2016-04-18 12:13, A Berger wrote:

Hi
How can I call a proc with args ?
....map(&:myproc(n))
# => unexpected '('

You could do some kind of partial function application to get a new proc
with argument "n" already fixed and that now only takes the one parameter
(an item from the mapped collection):

def partial_apply(f, x)
  proc { |y| f.call(x, y) }
end

myproc = proc { |x, y| x + y }

collection = [1, 2, 3, 4]

collection.map(&partial_apply(myproc, 1000))
# => [1001, 1002, 1003, 1004]

Just one possible work-around.

And: How can I use & with a 'normal' method?

def ss(n)
  print n+1
end

....map(&:ss(n)) # or sg else, is there a shorter/better/working form
for/instead of:
....map { |x| x.ss(n) }

Thanks
Berg

I think Andrew's response covered the rest.

···

On Mon, Apr 18, 2016 at 1:13 PM, A Berger <aberger7890@gmail.com> wrote:

--
Kendall Gifford
zettabyte@gmail.com

Just a personal pet peeve of mine:

On 19 April 2016 at 05:13, A Berger <aberger7890@gmail.com> wrote:​​

....map(&:ss(n)) # or sg else, is there a shorter/better/working form
for/instead of:
....map { |x| x.ss(n) }

Ever since​ the '&' toproc/call magic stuff hit the big time in enumerators
people have had this obsession with not writing out blocks in their Ruby
code. Why is this? What is wrong with the second line above? It's concise
and clear, and it's been standard Ruby syntax for as long as I can remember.

Does everyone just want to write declarative code, rather than functional?
Is that all it is?

Remember, if you want to write code with all sorts of magic symbols and the
fewest keystrokes possible and all that, Perl exists.

And stay off my lawn, dang whipper-snappers.

Cheers

···

--
  Matthew Kerwin
  http://matthew.kerwin.net.au/

Thanks for all that great answers!

Matthew: Especially with a non-US kbd, you will dislike {} and |x| ...
I will see what to prefer, just good to know what can be done :slight_smile:

Berg