将数组中的哈希数组拆分为切片

时间:2014-10-29 16:16:23

标签: ruby

假设你有一个字符串

initial_message = "My dear cousin bill!"

我把这个N字符串放在一个哈希数组中(其中每个字母都是键,值是A = 0,B = 1,C = 2等)。

hsh_letter_values = Hash[('a'..'z').zip (0..25).to_a] #Map letters to numbers in a hash
clean_message = initial_message.tr('^a-zA-Z0-9','').downcase #remove non-letters
char_map = clean_message.each_char.map { |i| { i => hsh_letter_values[i] } } #map each letter of message to corresponding number

然后我将char_map拆分为16个切片。

char_split_map = char_map.each_slice(16).to_a

我想将每个16个字符的切片拆分成4个切片,同时保持散列的顺序相同。

结果应该如下:

[[[{"m"=>12}, {"y"=>24}, {"d"=>3}, {"e"=>4}],[{"a"=>0}, {"r"=>17}, {"c"=>2}, {"o"=>14}], [{"u"=>20}, {"s"=>18}, {"i"=>8}, {"n"=>13}], [{"b"=>1}, {"i"=>8}, {"l"=>11}, {"l"=>11}]]

我计划从每列添加每个字母的值以获得四个总和(C1,C2,C3,C4) 所以对于第一列,它将是12 + 0 + 20 + 1。

这是我到目前为止http://repl.it/2cd/1

对于我做错了什么或处理这种情况的更好方法的任何帮助?

2 个答案:

答案 0 :(得分:0)

我可能采用略有不同的方法:

initial_message = "My dear cousin bill!"
chars = initial_message.tr('^a-zA-Z0-9','').downcase.chars
char_map = ->(char) { char.ord - 97 }

results = chars.each_slice(4).each_slice(4).map do |array| 
  array.transpose.map {|column| column.reduce(0) {|res, letter| res + char_map[letter]} }
end

results.inspect     => '[[33, 67, 24, 42]]'

这不符合您在问题中描述的中间步骤,但这可能是实现最终结果的更好方法。

答案 1 :(得分:0)

一种方式,从消息开始:

msg = "My dear cousin bill!"

arr = msg.downcase.gsub(/[^a-z]/,'').chars.each_slice(4).to_a
  #=> [["m", "y", "d", "e"],
  #    ["a", "r", "c", "o"],
  #    ["u", "s", "i", "n"],
  #    ["b", "i", "l", "l"]]

4.times.map { |i| arr.reduce(0) { |t,a| t + (a[i]||?a).ord-?a.ord } }
  #=> [33, 67, 24, 42]

msg = "My dearest cousin bill!"

arr = msg.downcase.gsub(/[^a-z]/,'').chars.each_slice(4).to_a
  #=> [["m", "y", "d", "e"],
  #    ["a", "r", "e", "s"],
  #    ["t", "c", "o", "u"],
  #    ["s", "i", "n", "b"],
  #    ["i", "l", "l"]]

4.times.map { |i| arr.reduce(0) { |t,a| t + (a[i]||?a).ord-?a.ord } }
  #=>[57, 62, 45, 43]