2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

初めてのRuby2 〜Array, Hash, シンボル〜

Last updated at Posted at 2019-06-18

自分の自分よる自分のためのRuby説明

3ヶ月前の自分へ
以前に書いた記事の続きです:raised_hands_tone1:

配列 Array

:star:配列とは : オブジェクトの入れ物
:point_up_tone1:入れ物は[](四角いかっこ)
:point_up_tone1:仕切りは , (カンマ)

foods=["じゃがりこ", "かにみそ", "するめ"]

↑この場合、
foodsが変数
[]の中身全体 : Arrayオブジェクト
食べ物一つ一つ : Stringオブジェクト

配列からの取り出し方
animals=["ねこ", "きりん", "すずめ"]
animals[0] →"ねこ"
animals[1]  →"きりん"

:warning:最初を取り出したい時は0だよ!

配列へ追加
animals=["ねこ", "きりん", "すずめ"]
animals.push("かば")
print animals → ["ねこ", "きりん", "すずめ", "かば"]
要素数を返す

配列の入れ物の中に何個の要素が入ってるか知りたいときは
:star2:sizeメソッド
:star2:lengthメソッド
sizeメソッドとlengthメソッドは一緒

print animals.size →4
print animals.length →4

配列の繰り返し処理

配列.each do|変数|
 繰り返したい処理
end 

例)

animals = ["ねこ", "きりん", "すずめ"]
animals.each do |animal|
 puts animal
end

→"ねこ"
 "きりん"
 "すずめ"

ハッシュ(Hash)

:point_up_tone1:ハッシュとは
キーと値の組を持つことができるオブジェクトの入れ物
なんでも入る

book = {"title" => 夢をかなえるゾウ, "author" => 水野敬也}
puts["title"]   →夢をかなえるゾウ
puts["author"]   →水野敬也

シンボル

:point_up_tone1:シンボルとは
ラベルとして使う文字列みたいなもの。先頭に : をつける
ハッシュと組み合わせて使うことが多い

book = {:title => "夢をかなえるゾウ", :author => "水野敬也"}
puts book[:title]  →"夢をかなえるゾウ"

:point_down_tone1:これでもOK(簡素化版)

book = {title: "夢をかなえるゾウ", author: "水野敬也"}
puts book[:title]  →"夢をかなえるゾウ"

ハッシュへ追加したい時

book = {:title => "夢をかなえるゾウ", :author => "水野敬也"}
book[:price] = 1000yen
↓
book = {:title => "夢をかなえるゾウ", :author => "水野敬也", :price => 1000yen}

ArrayとHashの使い分け

:sunny:Array : 順番が決まっている入れ物
・並び順が大切なもの
・データを重複させたい場合

:sunny:Hash : キー(名札)をつけられる入れ物
・順番が保持される
・キーが重複しない場合に利用

2
0
2

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
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?