Created
August 9, 2012 05:47
-
-
Save adarapata/3301432 to your computer and use it in GitHub Desktop.
Readingtechnicalbooks0x01.homework0x03
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
h = { | |
'heteml' => 'kaba', | |
'muumuu' => 'kuma', | |
'lolipop' => 'ozisan' | |
} | |
another_hash = { | |
"hatena" => "cinnamon", | |
"oracle" => "candy", | |
} | |
sqale = { | |
"production" => { | |
"app" => [ | |
"app001.sqale.jp", | |
"app002.sqale.jp", | |
], | |
"users" => [ | |
"users001.sqale.jp", | |
"users002.sqale.jp", | |
], | |
} | |
} | |
# 1.キー heteml が存在するか確認する | |
h['heteml'].nil? | |
h.key? 'heteml' | |
h.include? 'heteml' | |
h.has_key? 'heteml' | |
# 2.値 kaba が存在するか確認する | |
h.value? 'kaba' | |
# 3.ハッシュから heteml を消す | |
h.delete 'heteml' | |
# 4.存在しないキーにアクセスすると 'unknown' を返すハッシュを作る | |
h.default = 'unknown' | |
# 5.ハッシュのキー全部を配列で返すメソッド | |
h.keys | |
# 6.ハッシュのキーをイテレーターで出力する | |
h.each { |key| puts "#{key}"} | |
# 7.ハッシュの値を全部を配列で返すメソッド | |
h.values | |
# 8.ハッシュの値をイテレーターで出力する | |
h.value { |v| puts v } | |
# 9.ハッシュのキーと値を イテレーターで出力する | |
h.each_pair { |key, value| puts "#{key}" + " " + "#{value}" } | |
h.each { |key, value| puts "#{key}" + " " + "#{value}" } | |
# another answer for 神様 | |
print h.map { |v| v.join(' ') }.join("¥n") | |
# 10.二つのハッシュを結合する | |
h.merge(another_hash) | |
# another answer for 神様 | |
Hash[*(h.to_a + another_hash.to_a).flattien] | |
# 11.複雑な構造にアクセスする | |
sqale["production"]["app"][0] | |
sqale["production"]["app"].first | |
# another answer for 神様 | |
def search(hash, arr) | |
key = arr.shift | |
return hash[key] if arr.empty? | |
return search(hash[key], arr) | |
end | |
search(sqale, ['production', 'app', 0]) |
訂正ありがとうございますー。ダブルとシングルは使い分け必要なんですね。
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
細かいですが、58 行目は、こうですねー↓
ダブルクォーテーションじゃないと、改行コードとして認識されないです。
あと、改行は、/n→\n ですね。