字符串填充和切片到固定长度

时间:2015-10-31 01:56:37

标签: arrays ruby string padding slice

对于一些只有1和0的随机长度数组,我需要这样做,以便开始和结束分别始终为001100

字符串形式的一些示例以提高可读性

"11010" => "00110100"
"01010" => "0010100"
"10000" => "00100"
"01100" => "001100"
"11111" => "001111100"
"00100" => "00100"
"00010" => "00100"
"00000" => ""    # cases with no 1's are ignored

我提出的代码只是使用shift / unshift push / pops直到

def norm(arr)
  (arr.index(1) > 2 ? arr.shift : arr.unshift(0)) until arr.index(1) == 2
  (arr.rindex(1) > arr.length-3 ? arr.push(0) : arr.pop) until arr.rindex(1) == arr.length-3
  arr
end

使用填充,切片等方法是否有更好的(某种?)方式?

3 个答案:

答案 0 :(得分:2)

您可以在0之前和之后1之前忽略任何1。所以,

def norm(arr)
  if arr.include?('1')
    ['0', '0'] + arr.slice(arr.index('1')..arr.rindex('1')) + ['0', '0']
  else
    []
  end
end

答案 1 :(得分:1)

而不是尝试做任何复杂的事情,我会这样做:

[
  "11010", # => "00110100"
  "01010", # => "0010100"
  "10000", # => "00100"
  "01100", # => "001100"
  "11111", # => "001111100"
  "00100", # => "00100"
  "00010", # => "00100"
  "00000", # => ""    # cases with no 1's are ignored
].each do |s|
  if s['1']
    s[/^0*1/] = '001'
    s[/10*$/] = '100'
  end
  puts s
end

运行它会导致:

# >> 00110100
# >> 0010100
# >> 00100
# >> 001100
# >> 001111100
# >> 00100
# >> 00100
# >> 00000

首先检查字符串是否包含1。如果确实如此,代码会替换任意数量的前导01 001,然后替换尾随1后跟任意数量的0 s与100

答案 2 :(得分:0)

您可以将String#gsub与正则表达式一起使用:

r = /
    \A0*   # match beginning of the string followed by zero or more zeroes
    (?=1)  # match 1 in a positive lookahead
    |      # or
    (?<=1) # match 1 in a positive lookbehind
    0*\z   # match zero of more zero's followed by the end of string
    /x     # regex "extended" or "free spacing" mode 

arr = %w| 11010 01010 10000 01100 11111 00100 00010 00000 |
  #=> ["11010", "01010", "10000", "01100", "11111", "00100", "00010", "00000"] 

arr.each { |s| puts "#{s} -> #{ s.gsub(r,'00') }" }
# 11010 -> 00110100
# 01010 -> 0010100
# 10000 -> 00100
# 01100 -> 001100
# 11111 -> 001111100
# 00100 -> 00100
# 00010 -> 00100
# 00000 -> 00000