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
a = {"Apple" => "Red color", "Orange" => "Orange color", "Banana" => "Yellow color", } | |
p a.sort{|n,m| n[1] <=> m[1]} | |
# ハッシュのsortでは一旦ハッシュを二次元配列に変換する | |
# [["Apple", "Red color"], ["Orange", "Orange color"], ["Banana", "Yellow color"]] | |
# n[1]の部分で、aには["Apple", "Red color"]のような要素が1つずつ入る | |
# その中のインデックス1番目ということは、a[1]の中身は、"Red color"となる(元々のキーと値のペアの、値の部分) | |
# 値が英語の文字列のため、それらをソートしてアルファベット順に並び替えられる。 |
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
# 正規表現の中の.は任意の1文字を表す。下記の場合oの後に4文字続く。 | |
p "hogehogehoge".slice(/o..../) | |
#=> "ogeho" | |
# 最初のハイフンは範囲指定(2-4、234のどれかにマッチ)で、末尾のハイフンは「-」という文字 | |
# スラッシュで囲まれていなくても、deleteメソッドなどの引数では文字列内で正規表現のような指定方法が使用できる。 | |
p "0123456789-".delete("^12-46-") | |
#=> "12346-" | |
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
hash = Hash.new { |h, k| "#{k}は存在しないキーです" } | |
p hash.default #=>nil | |
p hash.default_proc #=>#<Proc:0x000014e9e367fe08> | |
p hash[:hoge] #=>"hogeは存在しないキーです" | |
puts "---" | |
hash.default_proc = proc { |h, k| "#{k}というキーは存在しません" } | |
p hash.default_proc #=>#<Proc:0x00001532a916ed60> | |
p hash[:hoge] #=>"hogeというキーは存在しません" |
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
a = [-1,2,3,4,5] | |
b = (4..6).to_a | |
puts "b:#{b}" | |
puts "---" | |
p a.inject(:+) + b.inject(:+) | |
puts "---" |