ruby 实现Array#pad和Array#pad!。每个方法都接受最小大小(非负整数)和可选的pad值作为参数。如果是

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ruby 实现Array#pad和Array#pad!。每个方法都接受最小大小(非负整数)和可选的pad值作为参数。如果是相关的知识,希望对你有一定的参考价值。


# PSEUDOCODE
# INPUT: array object takes a non-negative integer minimum array size, 
# optional value to pad which defaults to nil
# OUPUT: array object (#pad! returnning the same object while #pad 
# will return a copy) which is padded conditional on its existing 
# attributes and the passed parameters

# STEPS: for #pad! [#pad will do the same, but make a copy prior to executing
# anything with the potential to modify it] if the array is smaller than the
# minimum size find the difference and push the value,  or nil if parameter
# omitted, to the end of the array  and return the array


# INITIAL 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


# 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/REFLECT  I worked on this problem during my first (not moderated)
# pairing session. Tackling pair coding was tough and this problem wasn't the
# easiest of ones we have seen thus far. Being the first challenge or required
# pre-phase 0 exercise that presented us with a class, we were thrown off from
# the start trying to agree on what to put for psuedocode INPUT. Further, I
# think we were nervous or overthinking the problem because we couldn't quite
# agree on what calculation needed to be done to test the length of the array
# against the minimum size and determine whether further action was needed. It
# was a learning experience in more ways than one. Ultimately, I came up with
# a working solution (INITIAL CODE) shortly after breaking with my pair. We
# reconviened the following day and worked through what we had come up with.

# While thinking about approaches for refactoring and checking which avenues my
# fellow boots took on the way to a solution, I wondered why I even called for
# if/else testing the length. A while statement would do this by definition and
# could easily replace and simplify my solution, if only a little. I look
# forward to looking into this problem more for the next challenge.

以上是关于ruby 实现Array#pad和Array#pad!。每个方法都接受最小大小(非负整数)和可选的pad值作为参数。如果是的主要内容,如果未能解决你的问题,请参考以下文章

Ruby - Array#<< 和 Array#push 之间的区别

从数组 ruby​​ 生成哈希键和值

ruby array

ruby 的 Hash.replace 或 Array.replace 有啥用?

ruby 检查Array项是否在另一个Array中

ruby 检查Array项是否在另一个Array中