使用&在rails上的ruby阻止sytax: [英] ruby on rails block sytax using &:
问题描述
所以说我有一个Question模型和Answer模型以及Question has_many Answers(这是一个选择题).
So say I have a Question model and an Answer model and Question has_many Answers (it's a multiple choice question).
假设问题是Question对象的集合.
Suppose that questions is a collection of Question objects.
为了收集所有答案,我可以这样做:
In order to collect all the answers I can do this:
questions.collect(&:answers)
两个问题:
-
此语法的确切含义是什么?是否扩展到
What precisely does this syntax mean? Does it expand to
questions.collect { |q| q.answers }
或者这里还有其他事情吗?
or is there something else going on here?
有没有办法做
questions.collect { |q| q.answers.shuffle }
使用相同的语法?
collect(&:answers.shuffle)
没有这样做.
我似乎在Web上的红宝石块的教程中找不到此内容,并且搜索不起作用(搜索引擎会忽略&::").我在一些继承的代码中找到了它.
I can't seem to find this in tutorials on ruby blocks on the web and searching for it doesn't work (search engines ignore "&:"). I found it in some inherited code.
谢谢
推荐答案
是的,第一个问题是N重复的,但是关于第二个问题:否,您不能链接方法. 但是,除了编写可能会让人迷惑的代码之外,没有什么可以阻止您创建自己的工具了:
Yes, the first question is N-duplicated, but regarding the second: no, you cannot chain methods. However, nothing stops you -other than writing code that may puzzle people- to create your own tool:
class Symbol
def to_proc
proc do |obj|
self.to_s.split(/\./).inject(obj, :send)
end
end
end
p ["1", "2", "3"].map(&:"to_i.succ")
# [2, 3, 4]
您甚至可以找到发送参数的方法,尽管它可能不会很漂亮.
You can even find ways to send arguments, though it won't probably be very beautiful.
这篇关于使用&在rails上的ruby阻止sytax:的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!