LoginSignup
0

More than 5 years have passed since last update.

【Ruby】Hashで遊んでみた

Last updated at Posted at 2016-12-20

はじめに

Rubyのhashで遊んでいたら思っていたより高機能だったのでメモ
そんな面白いものじゃありません
hashを使ったことない人向けです

ソース

hashtest.rb
myhash = Hash.new(0)

gets.split(" ").map{|d| myhash[d.to_i]+=1}

p myhash
p myhash.to_a
p myhash.size
puts "== max/min key (pair)"
p myhash.max
p myhash.min
puts "== max/min values =="
p myhash.values
p myhash.values.max
p myhash.values.min

puts "== each values=="
p myhash.each{|key,hash| puts"#{key}:#{hash} times"}

puts "== imidiate increment =="
p myhash[100] += 5

puts "== recursive access =="
p myhash[myhash[myhash[100]]]

puts "== set =="
p myhash.update({4=>5})

puts "== key searched from values =="
p myhash.key(1)

puts "== sum of the values=="
p myhash.values.inject(:+)

#ダメな例
puts " ##== this is NOT sum ==## "
p myhash.inject(:+)

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0