我想将一个参数传递给使用define_method定义的方法,我该怎么做?
我注意到我发现**Ruby 2.1.1中的(双splat)运算符是一个非常令人惊讶的行为.
当在a之前使用键值对时**hash,哈希保持不变; 但是,当键值对仅在之后使用时**hash,哈希值将被永久修改.
h = { b: 2 }
{ a: 1, **h } # => { a: 1, b: 2 }
h # => { b: 2 }
{ a: 1, **h, c: 3 } # => { a: 1, b: 2, c: 3 }
h # => { b: 2 }
{ **h, c: 3 } # => { b: 2, c: 3 }
h # => { b: 2, c: …Run Code Online (Sandbox Code Playgroud) 使用单个splat,我们可以将数组扩展为多个参数,这与直接传递数组非常不同:
def foo(a, b = nil, c = nil)
a
end
args = [1, 2, 3]
foo(args) # Evaluates to foo([1, 2, 3]) => [1, 2, 3]
foo(*args) # Evaluates to foo(1, 2, 3) => 1
Run Code Online (Sandbox Code Playgroud)
但是,使用关键字参数,我看不出任何差异,因为它们只是哈希的语法糖:
def foo(key:)
key
end
args = { key: 'value' }
foo(args) # Evaluates to foo(key: 'value') => 'value'
foo(**args) # Evaluates to foo(key: 'value') => 'value'
Run Code Online (Sandbox Code Playgroud)
除了良好的对称性,是否有任何实际的理由在方法调用上使用双splats?(请注意,这与在方法定义中使用它们不同)
我第一次遇到 JavaScript 中的 spread( ...) 语法,并且逐渐欣赏它可以做的许多事情,但我承认我仍然觉得它很奇怪。其他语言中是否有等效项?在那里它叫什么?
我来自 Python 和 Java 背景,只有 CSS、HTML、Ruby 的基本知识,并尝试使用 Ruby on Rails 学习 Web 开发。我正在尝试按照Michael Hartl上的教程进行操作。我不明白代码post清单 7.23 中的方法在做什么参数。
require 'test_helper'
class UsersSignupTest < ActionDispatch::IntegrationTest
test "invalid signup information" do
get signup_path
assert_no_difference 'User.count' do
post users_path, params: { user: { name: "",
email: "user@invalid",
password: "foo",
password_confirmation: "bar" } }
end
assert_template 'users/new'
end
end
Run Code Online (Sandbox Code Playgroud)
从我在API 中的跟踪来看,它接受了两个都是字符串的非可选参数,但是在代码清单 7.23params:中,第二个参数中突然出现了哈希语法,这让我很困惑。任何人都可以启发我吗?
我有一个看起来像这样的哈希:
hash = {
'key1' => ['value'],
'key2' => {
'sub1' => ['string'],
'sub2' => ['string'],
},
'shippingInfo' => {
'shippingType' => ['Calculated'],
'shipToLocations' => ['Worldwide'],
'expeditedShipping' => ['false'],
'oneDayShippingAvailable' => ['false'],
'handlingTime' => ['3'],
}
}
Run Code Online (Sandbox Code Playgroud)
我需要转换每个值,它是数组中的单个字符串,以便它最终像这样:
hash = {
'key1' => 'value' ,
'key2' => {
'sub1' => 'string' ,
'sub2' => 'string' ,
},
'shippingInfo' => {
'shippingType' => 'Calculated' ,
'shipToLocations' => 'Worldwide' ,
'expeditedShipping' => 'false' ,
'oneDayShippingAvailable' => 'false' ,
'handlingTime' => '3' , …Run Code Online (Sandbox Code Playgroud) ** 在 Ruby 中是什么意思?
例子
下面提到的代码片段并得到:
1 ** 5 # => 1
43 ** 67 # => 27694053307656599023809257877241042019569010395053468294153499816223586030238186389799480520831161107426185107
Run Code Online (Sandbox Code Playgroud)
问题