SB    D SB D - 3 months ago 10
Ruby Question

Ruby: How can I dynamically build a hash from user input

I have a hash like this below

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


now user input 1 then I will fetch first 5 if user input 2 then 6 to next 5 means 6 to 11

How can I acheieve this by a best way

Answer
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} 
Comments