Ruby:如何从用户输入动态构建哈希

时间:2016-08-10 05:32:57

标签: ruby

我有这样的哈希

h = {a: 1, b: 2, c: 3, d: 4.....z: 26}

现在用户输入1然后如果用户输入2然后6到下一个5意味着6到11,我将获取前5个

我怎样才能以最佳方式实现这一目标

4 个答案:

答案 0 :(得分:5)

h = {a: 1, b: 2, c: 3, d: 4.....z: 26}

user_input = 1

Hash[h.to_a[((user_input - 1) * 5 )..( (user_input * 5) - 1)]]
#=> {:a=>1, :b=>2, :c=>3, :d=>4, :e=>5} 

答案 1 :(得分:2)

我认为问题涉及任意哈希。

<强>代码

三种选择:

#1

def select_em(h, which_block_5)
  select_range = (5*which_block_5 - 4)..(5*which_block_5)
  h.select.with_index(1) { |_,i| select_range.cover?(i) }
end

#2

def select_em(h, which_block_5)
  select_array = Array.new(5*(which_block_5-1),false) +
                 Array.new(5,true) +
                 Array.new(h.size-5*(which_block_5),false)
  h.select { select_array.shift }
end

请注意

 select_array = Array.new(5*(which_block_5-1),false) +
                Array.new(5,true) +
                Array.new(26-5*(which_block_5),false)
   #=> [false, false, false, false, false, true, true, true, true, true,
   #    false, false, false, false, false, false, false, false, false,
   #    false, false, false, false, false, false, false] 

#3

def select_em(h, which_block_5)
  start = 5*which_block_5 - 4
  stop  = start + 4
  h.select.with_index(1) { |_,i| (i==start..i==stop) ? true : false }
end

此方法使用Ruby的flip-flop operator

所有这些方法都使用Hash#select(返回哈希),而不是Enumerable#select(返回数组)。

<强>实施例

h = {:a=>1, :b=>2, :c=>3, :d=>4, :e=>5, :f=>6, :g=>7, :cat=>"meow",  :dog=>"woof",
     :h=>8, :i=>9, :j=>10, :k=>11, :l=>12, :m=>13, :n=>14, :o=>15,
     :p=>16, :q=>17, :r=>18, :s=>19, :t=>20, :u=>21, :v=>22, :w=>23,
     :x=>24, :y=>25, :z=>26} 

select_em(h, 1)
  #=> {:a=>1, :b=>2, :c=>3, :d=>4, :e=>5} 
select_em(h, 2)
  #=> {:f=>6, :g=>7, :cat=>"meow", :dog=>"woof", :h=>8} 
select_em(h, 3)
  #=> {:i=>9, :j=>10, :k=>11, :l=>12, :m=>13} 
select_em(h, 4)
  #=> {:n=>14, :o=>15, :p=>16, :q=>17, :r=>18} 

答案 2 :(得分:0)

以下是我要做的事情:

char_ary = ('a'..'z').to_a
start_idx = (input - 1) * 5
subary = char_ary.slice(start_idx, 5)
subary.inject({}) do |h, c|
  h[c.to_sym] = char_ary.index(c) + 1
  h
end

这并不需要使用所有字母表定义哈希值。

答案 3 :(得分:-1)

所以你可以简单地使用切片数组函数来分割出来。

   alphabets = [*('a'..'z')].collect.with_index{ |key,index| { key => index+1  }  } 
   user_input = 1 # Capture user input here. 
   part_of_array = alphabets[( (user_input - 1) * 5 )..( (user_input * 5) - 1)]

转换为简单的一个哈希使用下面的代码。

part_of_array = eval(alphabets[( (user_input - 1) * 5 )..( (user_input * 5) - 1)].to_s.gsub("{","").gsub("}",""))

如果您有任何问题,请告诉我。