2

I am trying to find the cleanest way to do something special for the first item in an array, then do something different for all the rest. So far I have something like this:

puts @model.children.first.full_name
@model.children[1..@model.children.count].each do |child|
  puts child.short_name
end

I don't like how I have to specify the count in the range. I would like to find a shorter way to specify "from the second item to the last". How can this be done?

4

5 回答 5

10

Ruby 使用 splat 运算符有一个很酷的方法*。这是一个例子:

a = [1,2,3,4]
first, *rest = *a
puts first # 1
puts rest # [2,3,4]
puts a # [1,2,3,4]

这是您重写的代码:

first, *rest = @model.children
puts first.full_name
rest.each do |child|
  puts child.short_name
end

我希望这有帮助!

于 2013-07-02T21:55:56.893 回答
6

您可以采用这种方法:

@model.children[1..-1].each do |child|
  puts child.short_name
end
于 2013-07-02T21:30:11.303 回答
4

您可能会使用drop

puts @model.children.first.full_name
@model.children.drop(1).each do |child|
  puts child.short_name
end
于 2013-07-02T21:30:56.550 回答
3

像这样的东西?:

puts @model.children.first.full_name
@model.children[1..-1].each do |child|
  puts child.short_name
end
于 2013-07-02T21:30:20.030 回答
0

你的标题说你想省略n元素,但 OP 文本只要求特别对待第一个元素。如果您对更通用的 nanswer 感兴趣,这里有一个简洁的选项:

n = 1 # how many elements to omit
@model.children.drop( n ).map( &:short_name ).each &method( :puts )
于 2013-07-02T22:18:28.247 回答