什么是星号变量*arr?
*arr = "sayuj"
=> ["sayuj"]
*arr = *%w{i am happy}
=> ["i", "am", "happy"]
*arr = %w{i am happy}
=> [["i", "am", "happy"]]
Run Code Online (Sandbox Code Playgroud) 为什么这个代码
Hash[*[[:first_name, 'Shane'], [:last_name, 'Harvie']].flatten]
Run Code Online (Sandbox Code Playgroud)
归还这个
{:first_name=>"Shane", :last_name=>"Harvie"}
Run Code Online (Sandbox Code Playgroud)
我知道Array#flatten.但这*意味着什么?我如何查找有关它的信息?
Ruby的文档将方法签名显示为:
start_with?([prefixes]+) ? true or false
Run Code Online (Sandbox Code Playgroud)
这对我来说看起来像一个数组,但事实并非如此.您可以传递单个字符串或各种字符串作为参数,如下所示:
"hello".start_with?("heaven", "hell") #=> true
Run Code Online (Sandbox Code Playgroud)
如何将数组作为参数列表传递?以下不起作用:
"hello".start_with?(["heaven", "hell"])
Run Code Online (Sandbox Code Playgroud) 我想做这个:
a << *b
Run Code Online (Sandbox Code Playgroud)
但这发生在irb:
1.9.3p327 :020 > a
=> [1, 2, 3, 4]
1.9.3p327 :021 > b
=> [5, 6, 7]
1.9.3p327 :022 > a << *b
SyntaxError: (irb):22: syntax error, unexpected tSTAR
a << *b
^
Run Code Online (Sandbox Code Playgroud)
我错过了什么吗?
我有一个方法可以接收单个对象或这些对象的数组。(我从中提取的 YAML 文件有时有foo: bar,有时有一个列表foo: [bar1, bar2]。)
每次调用此方法时,它都应该转换一个或多个值,并将它们添加到内部数组中。
我原来有这个:
class YamlEater
def initialize
@foos = []
end
def add(o)
if o.is_a?(Array)
o.each{ self.add(_1) }
else
@foos << FooItem.new(o)
end
end
end
Run Code Online (Sandbox Code Playgroud)
在我需要在许多不同的方法中使用该模式之后,我将其更改为非递归、更简洁的版本,该版本非常繁重,也许只有高尔夫球手才会喜欢:
def add(o)
@foos.push(*[*o].map{ FooItem.new(_1) })
end
Run Code Online (Sandbox Code Playgroud)
我认为有一种更优雅的方法可以实现相同的目标,并希望有人能分享。
Ruby的新手,我正在尝试接受方法中的多个splat参数.我想我理解为什么它给我编译错误,但我不知道如何解决它.任何有关如何在参数中使用多个splats的帮助都会有所帮助.提前感谢您的任何指导.
def find_max_expenses(salary, save_prcnt, *pre_ret_g_rates, *post_ret_g_rates, epsilon)
years = pre_ret_g_rates.count
savings = nest_egg_variable(salary, save_prcnt, pre_ret_g_rates)
savings = savings[-1]
low = 0
high = savings
expenses = (low + high) / 2
# can use the [-1] at the end is equivalent to the code below
remaining_money = post_retirement(savings, post_ret_g_rates, expenses) #[-1]
remaining_money = remaining_money[-1]
while remaining_money > epsilon # the value we want to stay above
if remaining_money > 0
low = expenses
else
high = expenses
end
expenses = …Run Code Online (Sandbox Code Playgroud) 我正在构建一个 Ruby 对象,该对象在其initialize方法中具有默认参数:
attr_accessor :one, :two, :three
def initialize(one: nil, two: nil, three: nil)
@one = one
@two = two
@three = three
end
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,这不是很 DRY,尤其是随着可初始化变量的数量增加。最终,我希望能够遍历每个参数并分配一个实例变量(splat 运算符和instance_variable_set?