问题描述
为了更好地理解 Ruby,我在网上冲浪时遇到了这段代码:
Trying to understand Ruby a bit better, I ran into this code surfing the Internet:
require 'rubygems'
require 'activeresource'
ActiveResource::Base.logger = Logger.new("#{File.dirname(__FILE__)}/events.log")
class Event < ActiveResource::Base
self.site = "http://localhost:3000"
end
events = Event.find(:all)
puts events.map(&:name)
e = Event.find(1)
e.price = 20.00
e.save
e = Event.create(:name => "Shortest event evar!",
:starts_at => 1.second.ago,
:capacity => 25,
:price => 10.00)
e.destroy
我特别感兴趣的是 events.map(&:name)
是如何工作的?我看到 events 是一个数组,因此它正在调用它的 map 方法.现在我的问题是,传递给地图创建的块在哪里?在这种情况下,符号 :name 是什么?我正在尝试了解它是如何工作的.
What I'm particularly interested in is how does events.map(&:name)
work? I see that events is an array, and thus it's invoking its map method. Now my question is, where is the block that's being passed to map created? What is the symbol :name in this context? I'm trying to understand how it works.
推荐答案
events.map(&:name)
完全等同于
events.map{|x| x.name}
它只是方便的语法糖.
有关更多详细信息,请查看 Symbol#to_proc
方法 此处.在这里, :name
被强制转换为 proc.
For more details, check out the Symbol#to_proc
method here. Here, :name
is being coerced to a proc.
顺便说一句,这里经常出现这种情况 - 很难用谷歌搜索或以其他方式搜索带有和号的冒号":)
By the way, this comes up often here - it's just very hard to google or otherwise search for 'the colon thing with an ampersand' :).
这篇关于map(&:name) 在这段 Ruby 代码中做了什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!