0
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 1 year has passed since last update.

Rubyのハッシュとキーワード引数であれ?となったこと

0
Last updated at Posted at 2023-04-23

はじめに

Rubyを触り始めて2週間ほどになりますが、ハッシュ、シンボル、キーワード引数まわりがエラーの源泉となっていました。
その中から、最近出会ったエラーの紹介をします。

Rubyのバージョン:3.0.6

Ruby 3.1.0 以降は挙動が異なるようです。

コメントより教えていただきました。@scivolaさんありがとうございます!

キーワード引数の場合

キーワード引数で受け取る場合、multiply(x: , y: )のようにキーワードだけ記入して、値は空にしておくことができます。
デフォルト値をつける場合はハッシュのように、値を書けばいいだけです。

multiply.rb
# デフォルト値なし
def multiply(x: , y: )
    puts x * y
end

# デフォルト値あり
def multiply_default(x: 4, y: 5)
    puts x * y
end

multiply(x: 2, y: 3)  #=> 6
multiply_default      #=> 20

ハッシュでのミス

その似通った見た目に引っ張られたのでしょう。
ハッシュでも同じことをしてしまいました。

numbers = {x: , y: } #=> syntax error, unexpected ','
numbers[:x] = 6
numbers[:y] = 7

multiply(**numbers)

ハッシュの初期化

ハッシュの初期化はhash = {}か、入れておきたい値がなくともnilを使ってhash = {x: nil, y: nil}のように値が必要です。  

numbers1 = {}
numbers1[:x] = 6
numbers1[:y] = 7

numbers2 = {x: nil, y: nil}
numbers2[:x] = 8
numbers2[:y] = 9

multiply(**numbers1) #=> 42
multiply(**numbers2) #=> 72  

おわりに

:の存在にずいぶん翻弄されましたが、やはり使っていくうちに慣れてきました。  
手を動かしてRubyに慣れていきたいと思います!

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