![](/img/trans.png)
[英]ruby 3 array argument splat with keyword arguments
[英]Is possible to define an argument with keyword that takes all succeeding arguments into an array in Ruby?
我知道定义方法时*
和**
作用,但我想知道是否可以这样做:
some_method("Hi", params: 1, 2, 3)
并具有如下定义:
def some_method(param, my_hash)
p param # "Hi"
p my_hash # { params: [ 1, 2, 3 ] }
end
问题本身就是在Student
编写answer_question
方法的清晰语法。 您会这样称呼: @student.answer_question question_obj, with: answer_instance, another_answer_instance
这就是我想要做的:
Question has_many Answer
Student has_many Answer through StudentAnswer
Answer has_many Student through StudentAnswer
我在StudentAnswer中保存了学生在调查中选择的答案(我需要一个额外的模型来将答案文本复制到Studentanswer中,以便在答案文本随时间变化时保存该答案)。
然后,我的语法实际上是
some_student.answer_question question, with: [answer1, answer2]
我想更清楚一点。
def some_method(param, my_hash = {})
p param
p my_hash
end
some_method('Hi', params: [1, 2, 3])
#=> "Hi"
#=> {:params=>[1, 2, 3]}
您不能忽略[]
并以以下方式调用方法:
some_method("Hi", params: 1, 2, 3)
这将导致语法错误,因为params: 1
不是有效的Ruby对象(它是语法糖,您可以将哈希作为最后一个参数传递而省略{}
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.