ruby 回顾其他人的解决方案,重构你的:填充数组

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ruby 回顾其他人的解决方案,重构你的:填充数组相关的知识,希望对你有一定的参考价值。

# Solution for Challenge: Review Others, Refactor Yours: Pad an Array. Started 2014-01-13T02:14:42+00:00


# FIRST ATTEMPT
## ORIGIAL CODE:
class Array
  def pad!(min_size, value = nil)
    if self.length < min_size
      (min_size - self.length).times do
        self << value
      end
    end
    return self
  end

  def pad(min_size, value = nil)
    new_array = self.dup
    if new_array.length < min_size
      (min_size - new_array.length).times do
        new_array << value
      end
    end
    return new_array
  end
end


## FIRST REFACTORED CODE:
class Array
  def pad!(min_size, value = nil)
    while self.length < min_size
      self << value
    end
      return self
  end

  def pad(min_size, value = nil)
    padded = self.dup
    while padded.length < min_size
      padded << value
    end
      return padded
  end
end


## REVIEW PEERS' & REFACTOR
class Array
  def pad!(min_size, value = nil)
    self << value until self.length >= min_size
    self   
  end

  def pad(min_size, value = nil)
    self.clone.pad!(min_size, value)
  end
end


# REVIEW/REFLECT  I learned a lot from reviewing fellow boots solutions for
# this problem. I paritularly like the use of until. I haven't often found a
# good use for this, yet, but this problem seems to present with just that. I
# spent quite some time reviewing #dup vs. #clone and still do not feel
# completely confident in the difference. I think it will become more evident
# when we start creating programs with some complexity and can more easily
# observe shallow vs. deep copies and its effects on the attribtues and
# behavior of objects.

以上是关于ruby 回顾其他人的解决方案,重构你的:填充数组的主要内容,如果未能解决你的问题,请参考以下文章

Ruby嵌套for循环以填充数组数组

ruby 用于重构面包店挑战的辅导/ GPS资源。可能的解决方案(高级)

ruby 用于重构面包店挑战的辅导/ GPS资源。可能的解决方案(高级)

转|Ruby 2015 年回顾

译文 | Ruby 2015 年回顾

重构许多嵌套 if 或链式 if 语句