其他Ruby Map速记符号 [英] Other Ruby Map Shorthand Notation

查看:69
本文介绍了其他Ruby Map速记符号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道地图的简写如下:

I am aware of the shorthand for map that looks like:

[1, 2, 3, 4].map(&:to_s)
> ["1", "2", "3", "4"]

有人告诉我这是以下简称:

I was told this is shorthand for:

[1, 2, 3, 4].map{|i| i.to_s}

这很合理.我的问题是:看来应该有一种更简单的书写方式:

This makes perfect sense. My question is this: It seems there should be an easier way to write:

[1, 2, 3, 4].map{|x| f.call(x)} 

对于某些步骤f.我知道我刚键入的方式并不需要很长的时间,但是我认为前面的示例都不存在速记.该示例似乎是对第一个示例的补充:我希望为每个x调用f,而不是为每个i调用i的to_s方法.

for some procedure f. I know the way I just typed isn't all that long to begin with, but I'd contend that neither is the previous example for which the shorthand exists. This example just seems like the complement to the first example: Rather than calling i's to_s method for every i, I wish to call f for every x.

这样的速记存在吗?

推荐答案

不幸的是,这种简写形式(称为"Symbol#to_proc")无法将参数传递给所调用的方法或块,因此您无法甚至不执行以下操作:

Unfortunately this shorthand notation (which calls "Symbol#to_proc") does not have a way to pass arguments to the method or block being called, so you couldn't even do the following:

array_of_strings.map(&:include, 'l') #=> this would fail

但是,您很幸运,因为您实际上不需要此快捷方式即可完成您想做的事情. &符可以将Proc或Lambda转换为块,反之亦然:

BUT, you are in luck because you don't actually need this shortcut to do what you are trying to do. The ampersand can convert a Proc or Lambda into a block, and vice-versa:

my_routine = Proc.new { |str| str.upcase }
%w{ one two three }.map &my_routine #=> ['ONE', 'TWO', 'THREE']

请注意在my_routine之前缺少冒号.这是因为我们不想通过找到方法并在其上调用.method:my_routine符号转换为proc,而是希望将my_routine Proc转换为块并将其传递给map

Note the lack of the colon before my_routine. This is because we don't want to convert the :my_routine symbol into a proc by finding the method and calling .method on it, rather we want to convert the my_routine Proc into a block and pass it to map.

知道这一点,您甚至可以映射本机Ruby方法:

Knowing this, you can even map a native Ruby method:

%w{ one two three }.map &method(:p)

method方法将采用p方法并将其转换为Proc,而&会将其转换为传递给map的块.结果,每个项目都被打印出来.这等效于此:

The method method would take the p method and convert it into a Proc, and the & converts it into a block that gets passed to map. As a result, each item gets printed. This is the equivalent of this:

%w{ one two three }.map { |s| p s }

这篇关于其他Ruby Map速记符号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆