加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby – 在特定位置插入哈希条目

发布时间:2020-12-17 03:42:24 所属栏目:百科 来源:网络整理
导读:给出哈希: {"set_filter"=["0"],"test1"=["=test1"],"test2"=["=test2"]} 如何在set_filter条目后添加新的键值对?预期的输出应该是这样的: { "set_filter" = ["0"],"test3" = ["=test3"],"test1" = ["=test1"],"test2" = ["=test2"]} 我想在哈希中的某个
给出哈希:

{"set_filter"=>["0"],"test1"=>["=test1"],"test2"=>["=test2"]}

如何在set_filter条目后添加新的键值对?预期的输出应该是这样的:

{
  "set_filter" => ["0"],"test3" => ["=test3"],"test1" => ["=test1"],"test2" => ["=test2"]
}

我想在哈希中的某个位置插入一个新的键值对.

解决方法

我建议你做以下事情:

>从哈希中提取密钥并找到给定密钥的索引
>如果要在给定键之后而不是之前插入给定对,则向索引添加一个
>将哈希转换为数组
>在计算索引之前在数??组中插入对(如果索引等于数组的大小,则在最后一对之后)
>将结果数组转换回哈希值

def insert_pair(h,key,pair,proximity=:before)
  h.to_a.insert(h.keys.index(key) + (proximity==:after ? 1 : 0),pair.first).to_h
end

h = {"set_filter"=>["0"],"test2"=>["=test2"]}
pair = {"test3"=>["=test3"]}

insert_pair(h,"set_filter",:after)
  #=> {"set_filter"=>["0"],"test3"=>["=test3"],"test2"=>["=test2"]} 
insert_pair(h,pair)
  #=> {"test3"=>["=test3"],"set_filter"=>["0"],"test2","test2"=>["=test2"],"test3"=>["=test3"]}

我做了:在默认值与Array#insert一致之前.

这是一种替代方法,它不会将哈希值转换为数组,修改数组然后将其转换回哈希值.相反,它将现有哈希分成两个哈希,在它们之间滑动单键哈希,然后将所有三个哈希合并为一个哈希.

def insert_pair(h,proximity=:before)
  keys = h.keys
  before_keys =
  case proximity
  when :before
    key==keys.first ? [[],keys] : keys.slice_before { |k| k == key }
  when :after
    keys.slice_after { |k| k == key }
  end.first
  h.select { |k,_| before_keys.include? k }.
    update(pair).
    update(h.reject { |k,_| before_keys.include? k }) 
end

insert_pair(h,"test3"=>["=test3"]}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读