如何将长ruby哈希打破成多行?

时间:2014-05-19 00:56:29

标签: ruby hash rspec

我有这个哈希:

  arr={ [0,1]=>[0,0,1,1], [0,2]=>[0,1,0,1], [0,3]=>[0,1,1,0], [1,2]=>[1,0,0,1], [1,3] =>[1,0,1,0], [2,3] => [1,1,0,0] }

我希望将它分成两行,因为它很长,为121个字符。我不是行长的贴纸,但我的指导线是80,这比我更喜欢

所以我试过

  arr={ [0,1] => [0,0,1,1], [0,2] => [0,1,0,1], [0,3] => [0,1,1,0] }
  arr.merge({[1,2] => [1,0,0,1], [1,3] => [1,0,1,0], [2,3] => [1,1,0,0]})

但我的测试失败了,错误就像

undefined method `[]' for nil:NilClass

我怎样才能更好地解决这个问题?一个选项是续行\,但这看起来并不特别。

arr={ [0,1]=>[0,0,1,1], [0,2]=>[0,1,0,1], [0,3]=>[0,1,1,0], \
[1,2]=>[1,0,0,1], [1,3] =>[1,0,1,0], [2,3] => [1,1,0,0] }

虽然我想我能做到

arr={ [0,1]=>[0,0,1,1], [0,2]=>[0,1,0,1], [0,3]=>[0,1,1,0], \
      [1,2]=>[1,0,0,1], [1,3] =>[1,0,1,0], [2,3] => [1,1,0,0] }

但这看起来像是用于缩进的空白维护气味。

有更整洁的选择吗?

3 个答案:

答案 0 :(得分:5)

arr = {
  [0,1] => [0,0,1,1], [0,2] => [0,1,0,1], [0,3] => [0,1,1,0],
  [1,2] => [1,0,0,1], [1,3] => [1,0,1,0], [2,3] => [1,1,0,0]
}

答案 1 :(得分:2)

我更愿意这样写:

arr = { 
  [0,1] => [0,0,1,1],
  [0,2] => [0,1,0,1],
  [0,3] => [0,1,1,0],
  [1,2] => [1,0,0,1],
  [1,3] => [1,0,1,0],
  [2,3] => [1,1,0,0] 
}

它更具可读性。另外我假设你知道使用数组作为键的后果吗?

答案 2 :(得分:2)

您对merge的尝试失败,因为#merge不会更改您调用它的对象,但它会返回一个新的合并对象。要使其正常工作,您需要使用#merge!

arr={ [0,1] => [0,0,1,1], [0,2] => [0,1,0,1], [0,3] => [0,1,1,0] }
arr.merge!([1,2] => [1,0,0,1], [1,3] => [1,0,1,0], [2,3] => [1,1,0,0])

但是,如同其他答案中所述,散列哈希非常简单,这是一种过度杀伤。