[英]Is possible to define an argument with keyword that takes all succeeding arguments into an array in Ruby?
I know what *
and **
do when defining a method, but I want to know if I can do this: 我知道定义方法时*
和**
作用,但我想知道是否可以这样做:
some_method("Hi", params: 1, 2, 3)
And have a definition like this: 并具有如下定义:
def some_method(param, my_hash)
p param # "Hi"
p my_hash # { params: [ 1, 2, 3 ] }
end
The problem itself is a clear syntax for writing a answer_question
method in a Student
. 问题本身就是在Student
编写answer_question
方法的清晰语法。 You would call like this: @student.answer_question question_obj, with: answer_instance, another_answer_instance
您会这样称呼: @student.answer_question question_obj, with: answer_instance, another_answer_instance
This is what i'm trying to do: 这就是我想要做的:
Question has_many Answer
Student has_many Answer through StudentAnswer
Answer has_many Student through StudentAnswer
I save which answers a student chose during a survey in StudentAnswer (I need an extra model to copy the answer text to studentanswer, to keep it saved if the answer text changes over time). 我在StudentAnswer中保存了学生在调查中选择的答案(我需要一个额外的模型来将答案文本复制到Studentanswer中,以便在答案文本随时间变化时保存该答案)。
Then, my syntax actually is 然后,我的语法实际上是
some_student.answer_question question, with: [answer1, answer2]
And I want to make it more clear. 我想更清楚一点。
def some_method(param, my_hash = {})
p param
p my_hash
end
some_method('Hi', params: [1, 2, 3])
#=> "Hi"
#=> {:params=>[1, 2, 3]}
You can not omit the []
and call the method as: 您不能忽略[]
并以以下方式调用方法:
some_method("Hi", params: 1, 2, 3)
It will cause you a syntax error, because params: 1
is not a valid Ruby object (it is a syntax sugar, that you can pass a hash as a last argument omitting the {}
). 这将导致语法错误,因为params: 1
不是有效的Ruby对象(它是语法糖,您可以将哈希作为最后一个参数传递而省略{}
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.