LoginSignup
0
0

More than 1 year has passed since last update.

ruby 練習問題1(アウトプット用)

Posted at
puts hash.keys
puts hash.values

上記のメソッドを実行した時に

one
two
three
1
2
3

とターミナルに表示されるような変数hashを作成するためのコードをシンボルを使って記述する問題。

以下、模範解答

hash = { one: 1, two: 2, three: 3 }

以下、解説

まずシンボルの理解。
シンボルを使うことで数値として扱うので処理速度が速くなる。よってハッシュはシンボルを使用することが多い。
シンボルを使ってキーを記述する方法はキーの後に:をつける。

hash = {キー: 値}

keysメソッド、valuesメソッド
両方ともHashクラスで使用できるメソッド。
オブジェクト.keysでハッシュに含まれるキーを取得

hash = { one: 1, two: 2, three: 3 }

puts hash.keys
one
two
three

オブジェクト.valuesでハッシュに含まれる値を取得

hash = { one: 1, two: 2, three: 3 }

puts hash.values
1
2
3
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