簡體   English   中英

Ruby在每個字符處將字符串分成7個字符塊

[英]Ruby split string into 7 character chunks at each character

如何在ruby中執行以下操作:

a = 1234567890

Split into strings 7 characters in length at each character:

=> [1234567,2345678,3456789,4567890]

謝謝!

編輯:謝謝大家的所有幫助。 對不起,我沒有說我嘗試過的內容(盡管沒有什么可以解決)。

a.to_s.each_char.each_cons(7).map{|s| s.join.to_i}
# => [1234567, 2345678, 3456789, 4567890]
a = 1234567890

# Convert to a string, then convert that string
# into an array of characters
chars = a.to_s.chars # => ["1", "2", "3", "4", "5", "6", "7", "8", "9", "0"]

slices = []

# Slice the array into groups of 7, with successive indices
chars.each_cons(7) do |cons|
  slices << cons.join # Join each 7-item array into a string and push it
end

p slices # => ["1234567", "2345678", "3456789", "4567890"]

您正在尋找的關鍵方法是each_cons

如果您喜歡使用一些更晦澀的Ruby方法,那么它也可以工作:

(0..a.to_s.size-7).map { |i| a.to_s.chars.rotate(i).take(7).join.to_i }
#=> [1234567, 2345678, 3456789, 4567890]
a.to_s.scan(/(?=(.{7}))/).map { |arr| arr.first.to_i }
  #=> [1234567, 2345678, 3456789, 4567890] 

(?= ... )是一個積極的前瞻。 (.{7})匹配捕獲組下一七個字符1.見字符串#掃描如何scan對待捕獲基團。 我們有

s = a.to_s
  #=> "1234567890" 
b = s.scan(/(?=(.{7}))/)
  #=> [["1234567"], ["2345678"], ["3456789"], ["4567890"]] 
b.map { |arr| arr.first.to_i }
  #=> [1234567, 2345678, 3456789, 4567890] 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM