⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 11 - building up a hash using injection.rb

📁 O Reilly Ruby Cookbook source code
💻 RB
字号:
collection = [ [1, 'one'], [2, 'two'], [3, 'three'],                [4, 'four'], [5, 'five']             ]collection.inject({}) do |hash, value|  hash[value.first] = value.last  hashend# => {5=>"five", 1=>"one", 2=>"two", 3=>"three", 4=>"four"}#---collection.dup.inject({}) { |hash, value| hash[value.first] = value.last }# IndexError: index 3 out of string#---Hash.new["key"] = "some value"                            # => "some value"#---collection.inject({}) do |hash, value|  hash.update value.first => value.lastend# => {5=>"five", 1=>"ontwo", 2=>"two", 3=>"three", 4=>"four"}#---class Array  def to_h(default=nil)    Hash[ *inject([]) { |a, value| a.push value, default || yield(value) } ]  endend#---a = [1, 2, 3]a.to_h(true)# => {1=>true, 2=>true, 3=>true}a.to_h { |value| [value * -1, value * 2] }# => {1=>[-1, 2], 2=>[-2, 4], 3=>[-3, 6]}#---

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -