Bio*_*ike 28 ruby perl hash nested
我是一个Perl人,我已经做了一段时间的哈希:
my %date;
#Assume the scalars are called with 'my' earlier
$date{$month}{$day}{$hours}{$min}{$sec}++
现在我正在学习Ruby,到目前为止我发现使用这个树是做许多键和值的方法.有没有办法使用我用Perl使用一行的简单格式?
@date = {
month => {
day => {
hours => {
min => {
sec => 1
}
}
}
}
}
mol*_*olf 48
不幸的是,没有简单实用的方法.一个Ruby等价物将是一个丑陋,丑陋的野兽,如:
((((@date[month] ||= {})[day] ||= {})[hours] ||= {})[min] ||= {})[sec] = 1
Run Code Online (Sandbox Code Playgroud)
但是,有一种方法可以为哈希中的缺失键分配默认值:
@date = Hash.new { |hash, key| hash[key] = {} }
# @date[:month] is set to a new, empty hash because the key is missing.
@date[:month][:day] = 1
Run Code Online (Sandbox Code Playgroud)
不幸的是,这不起作用.
...除非你自己创造 ; 很好的Ruby!
class Hash
def self.recursive
new { |hash, key| hash[key] = recursive }
end
end
@date = Hash.recursive
@date[month][day][hours][min][sec] = 1
# @date now equals {month=>{day=>{hours=>{min=>{sec=>1}}}}}
Run Code Online (Sandbox Code Playgroud)
但请记住,所有未设置的值现在都是,{}而不是nil.
ops*_*psb 18
这里有几个选项类似于@molf给出的答案,但没有猴子补丁.
使用工厂方法:
def hash_tree
Hash.new do |hash, key|
hash[key] = hash_tree
end
end
@date = hash_tree
@date[month][day][hours][min][sec] = 1
Run Code Online (Sandbox Code Playgroud)
使用自定义类:
class HashTree < Hash
def initialize
super do |hash, key|
hash[key] = HashTree.new
end
end
end
@date = HashTree.new
@date[month][day][hours][min][sec] = 1
Run Code Online (Sandbox Code Playgroud)
Xav*_*hay 17
->f{f[f]}[->f{Hash.new{|h,k|h[k]=f[f]}}]
Run Code Online (Sandbox Code Playgroud)
明显.
小智 15
与上面给出的lambda表达式相比,这更简单,也在一行中:
Hash.new {|h,k| h[k] = Hash.new(&h.default_proc) }
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
14916 次 |
| 最近记录: |