# default value nil
my_hash = {
"a" => 28
}
puts my_hash["b"] == nil
# nil is a special value we have in Ruby.
# basic represents nothingness or emptiness.
puts my_hash["a"] == nil
------------------------------------------------
# =>
true
false
# Hash.new(default)
my_hash = Hash.new(0) # default 값을 0으로 줬음
puts my_hash # my hash 라는 저장 장소에 아무것도 없어서 빈것으로 나옴
puts my_hash["a"] # key 값이 없으므로 default 값을 0으로 함.
puts my_hash["b"]
my_hash = Hash.new("hello") # default 값 == hello
my_hash["b"] = "goodbye" # b와 c 의 key value 값을 각각 goodbye와 1 로 assign 해줌
my_hash["c"] = 1
puts my_hash["c"]
puts my_hash["d"]
puts my_hash
-----------------------------
#=>
{}
0
0
1
hello
{"b"=>"goodbye", "c"=>1}
counter = Hash.new(0)
str = "bootcamp prep"
str.each_char do |char|
counter[char] += 1
end
puts counter
------------------------
#=>
{"b"=>1, "o"=>2, "t"=>1, "c"=>1, "a"=>1, "m"=>1, "p"=>3, " "=>1, "r"=>1, "e"=>1}
counter = Hash.new(0)
str = "bootcamp prep"
str.each_char do |char|
puts char
counter[char] += 1
puts counter
end
------------------------
#=>
b
{"b"=>1}
o
{"b"=>1, "o"=>1}
o
{"b"=>1, "o"=>2}
t
{"b"=>1, "o"=>2, "t"=>1}
c
{"b"=>1, "o"=>2, "t"=>1, "c"=>1}
a
{"b"=>1, "o"=>2, "t"=>1, "c"=>1, "a"=>1}
m
{"b"=>1, "o"=>2, "t"=>1, "c"=>1, "a"=>1, "m"=>1}
p
{"b"=>1, "o"=>2, "t"=>1, "c"=>1, "a"=>1, "m"=>1, "p"=>1}
{"b"=>1, "o"=>2, "t"=>1, "c"=>1, "a"=>1, "m"=>1, "p"=>1, " "=>1}
p
{"b"=>1, "o"=>2, "t"=>1, "c"=>1, "a"=>1, "m"=>1, "p"=>2, " "=>1}
r
{"b"=>1, "o"=>2, "t"=>1, "c"=>1, "a"=>1, "m"=>1, "p"=>2, " "=>1, "r"=>1}
e
{"b"=>1, "o"=>2, "t"=>1, "c"=>1, "a"=>1, "m"=>1, "p"=>2, " "=>1, "r"=>1, "e"=>1}
p
{"b"=>1, "o"=>2, "t"=>1, "c"=>1, "a"=>1, "m"=>1, "p"=>3, " "=>1, "r"=>1, "e"=>1}
str = "mississippi river"
count = Hash.new(0) # this is only we can choose the default value. value를 정하지 않으면 nil이 된다. nil에 숫자를 더할 수 없으므로 nil이라면 작동안됨.
str.each_char { |char| count[char] += 1 }
print count
puts
print count.sort_by {|k, v| v} # key 또는 value 값을 sorting 해준다. incresing value.
puts
print count.sort_by {|k, v| k} # here, the order of the alphabet
-----------------------------------
#=>
{"m"=>1, "i"=>5, "s"=>4, "p"=>2, " "=>1, "r"=>2, "v"=>1, "e"=>1}
[["e", 1], [" ", 1], ["v", 1], ["m", 1], ["r", 2], ["p", 2], ["s", 4], ["i", 5]]
[[" ", 1], ["e", 1], ["i", 5], ["m", 1], ["p", 2], ["r", 2], ["s", 4], ["v", 1]]
str = "mississippi river"
count = Hash.new(0)
str.each_char { |char| count[char] += 1 }
sorted = count.sort_by {|k, v| v}
print sorted[-1][0]
puts
----------------------------------------
# =>
i