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 3 years have passed since last update.

Rubyの関数と引数色々

Last updated at Posted at 2021-12-20

忘れがちな使い方と存在確認方法をセットでお届け

名前付き引数

ユースケース:
引数を必須にしたい
引数の数が多い

# 引数がなくても許される
def greet(name, message)
  p "Hi #{name}, #{message}"
end

greet('tom') # "Hi tom, undefined"

# 引数がないと許されない
def greet(name:, message:)
  p "Hi #{name}, #{message}"
end

# 名前も渡してね
greet('tom') # expected kwargs (ArgumentError)
# 必須だよ
greet(name:'tom') # missing keyword: message (ArgumentError)
# 正解
greet(name:'tom', message: 'how are you') # "Hi tom, how are you"

可変長引数

ユースケース:
汎用的な関数を作る
引数に渡すケース、わたさないケースがある

配列でとる

# 複数の値を配列でとれる
def greet(*args)
  p "args: #{args}"
end
greet('hi', 'hello', 'yo')
# "args: hi,hello,yo"

# 指定する
def greet(*args)
  p "arg[0]: : #{args[0]}"
end
greet('hi', 'hello', 'yo')
# "arg[0]: : hi"

# 存在確認する
def greet(*args)
  p args.include?('おはよう')
end
greet('hi', 'hello', 'yo')
# false

ハッシュでとる

# 複数の値をHashでとる
def greet(**args)
  p "args: #{args}"
end
greet(arg1:'hi', arg2:'hello', arg3:'yo')
# "args: {"arg1"=>"hi", "arg2"=>"hello", "arg3"=>"yo"}"

# 指定する
def greet(**args)
  p "arg[:arg1]: : #{args[:arg1]}"
end

# 存在確認する
def greet(**args)
  args[:args4].nil?
end
greet(arg1:'hi', arg2:'hello', arg3:'yo')
# true

可変長引数を併用する

def greet(*array, **hash)
  puts "array: #{array}"
  puts "hash : #{hash}"
end

greet('tom', 'bob', message: 'hi', message2: 'yo')
# array: tom,bob
# hash : {"message"=>"hi", "message2"=>"yo"}

# さすがにこれは怒られる
greet('tom', message: 'hi', 'bob', message2: 'yo') # SyntaxError
0
0
1

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?