Skip to content

Instantly share code, notes, and snippets.

@shinokada
Created June 9, 2014 06:21
Show Gist options
  • Save shinokada/0e43c6e6102190e03fd3 to your computer and use it in GitHub Desktop.
Save shinokada/0e43c6e6102190e03fd3 to your computer and use it in GitHub Desktop.
# I struggled how to add input data to an array in a hash value and these art some
# ways to do. [See more examples](http://judge.u-aizu.ac.jp/onlinejudge/solution.jsp?pid=0105#6).
#Using an array hash[word] = [page.to_i]
# and using has_key?
hash = {}
while n = gets
word, page = n.split
hash.has_key?(word) ? hash[word] << page.to_i : hash[word] = [page.to_i]
end
# Using ||=
# [Read this](http://www.rubyinside.com/what-rubys-double-pipe-or-equals-really-does-5488.html)
$<.each_line do |line|
word, page = line.split
hash[word] ||= []
hash[word] << page.to_i
end
# Using hash.key?
dic = {}
while line = gets
k, v = line.chomp.split
if dic.key?(k)
dic[k] << v.to_i
else
dic.store(k, [v.to_i])
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment