简体   繁体   English

使用本机方法替换冗长的代码块(Ruby on Rails)

[英]Replacing a verbose code block using native methods (Ruby on Rails)

I've been trying to learn the included methods with Rails and coming across situations where it seems like there should be better/cleaner ways of completing the same task, but I'm not sure how to improve. 我一直在尝试学习Rails包含的方法,并且遇到了似乎应该有更好/更干净的方法来完成同一任务的情况,但是我不确定如何进行改进。

The one I've hit most recently is as follows, where I have an array of hashes passed in as a parameter. 我最近遇到的一个如下,其中有一个作为参数传入的哈希数组。 If the array has less than 5 elements then I initialize elements until there are 5 total. 如果数组的元素少于5个,那么我将初始化元素,直到共有5个元素为止。

def do_stuff(numbers)
  raise "Maximum of 5 numbers can be defined in numbers array." if numbers.count > 5
  blank_range = (numbers.count-1)..5
  if blank_range.count > 0
    blank_range.each do |i|
      numbers[i] = {"entry" = " "}
    end
  end
end

This is a very basic example of what I'm wanting, though it's a pattern I've found myself using a few times. 这是我想要的非常基本的示例,尽管这是我发现自己使用过几次的模式。 Is there a way of doing this built in? 有内置的方法吗?

I think method #fill is what you need. 我认为方法#fill是您需要的。 It takes three arguments - an object to append to array and a range to fill with that object. 它需要三个参数-一个要追加到数组的对象和一个要用该对象填充的范围。

numbers.fill({ 'entry' => ' ' }, numbers.size...5)

So { 'entry' => '' } is your object, numbers.size is a starting position and 5 is the end position. 因此{ 'entry' => '' }是您的对象, numbers.size是起始位置, 5是结束位置。

If numbers.size is 5 it doesn't fill in anything. 如果numbers.size为5,则不会填写任何内容。

http://www.ruby-doc.org/core-2.1.2/Array.html#method-i-fill http://www.ruby-doc.org/core-2.1.2/Array.html#method-i-fill

The Ruby documentation for the Array class would be a great place to start. Array类的Ruby文档将是一个很好的起点。 There you'll find different ways to construct and manipulate arrays. 在那里,您会发现构造和操作数组的不同方法。

For example, to construct an array of 3 single space strings: 例如,要构造一个由3个单空格字符串组成的数组:

[" "] * 3         => [" ", " ", " "]
Array.new(3, " ") => [" ", " ", " "]

You could then use + to concatenate arrays like Array.new(3, " ") + numbers . 然后,您可以使用+连接Array.new(3, " ") + numbers

The Array class includes Enumeration , as does Range . Array类包括Enumeration ,以及Range When constructing an array from something else, inject can be useful. 当用别的东西构造一个数组时, inject可能是有用的。

Something like (1..3).inject(numbers) { |numbers, i| numbers.unshift(" ") } (1..3).inject(numbers) { |numbers, i| numbers.unshift(" ") } (1..3).inject(numbers) { |numbers, i| numbers.unshift(" ") }

Or maybe 3.times { numbers.unshift(" ") } 也许是3 3.times { numbers.unshift(" ") }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM