LoginSignup
0
0

More than 3 years have passed since last update.

Ruby学習3

Posted at

メソッドとか色々3

現在、Ruby技術者認定試験silverを取得するべく勉強中です。
言語に対する理解がまだまだなので、基本的な事からアウトプットしていきます。

配列の生成

通常の配列の生成はこう

mr_children = ["GIFT", "himawari", "simple"] #角カッコの中に要素を格納
p mr_children

=> ["GIFT", "himawari", "simple"]

%記法を使うと、カンマやクォーテーションが消えて少しスッキリする

mr_children = %w(GIFT himawari simple)
p mr_children

=> ["GIFT", "himawari", "simple"]

補足-要素の追加と挿入

mr_children = %w(GIFT himawari simple)
mr_children << "over" #配列の一番最後に要素を追加
p mr_children

=> ["GIFT", "himawari", "simple", "over"]

mr_children.insert(1, "エソラ") #第一引数で添字を指定し、そこに要素を挿入
p mr_children

=> ["GIFT", "エソラ", "himawari", "simple", "over"]

配列の演算(*)

mr_children = %w(GIFT himawari simple)
p mr_children * 3 #数値を掛けた場合

=> ["GIFT", "himawari", "simple","GIFT", "himawari", "simple","GIFT", "himawari", "simple"]
mr_children = %w(GIFT himawari simple)
p mr_children * ";" #文字列を掛けた場合
=> "GIFT;himawari;simple"
# 指定した文字列を挟み、要素を連結した文字列が返される

正規表現とscanメソッドメモ

s = "To be or not to be, that is the question." #変数sに文字列を定義
hash = Hash.new(0) #Hashクラスのインスタンス(中身は空)を生成
s.scan(/\w+/) {|i| hash[i] += 1}
#マッチした文字列を配列で取得。配列の値をブロック変数iに渡し、hashのキーとして定義。対応する値に数値の1を足す。
p hash

=> {"To"=>1, "be"=>2, "or"=>1, "not"=>1, "to"=>1, "that"=>1, "is"=>1, "the"=>1, "question"=>1}
# 単語毎の出現回数を割り出した。

これ→/\w+/ のメモ
\w => 英数字、アンダーバー
+ => 直前の文字が一回以上繰り返す場合にマッチ
つまり、「英数字かアンダーバーを単語単位でマッチさせる」記述。

scanメソッドは正規表現にマッチした文字列を配列で返す。ハッシュのキーに格納される前はどういう形になっているかというと、

s = "To be or not to be, that is the question."
p s.scan(/\w+/)

=> ["To", "be", "or", "not", "to", "be", "that", "is", "the", "question"]

単語で切り分けられた刺身みたいな状態。

To_Be_Continued...

0
0
0

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
0