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

【Ruby】デフォルト引数を使わないとこうなる

Posted at

はじめに

「デフォルト引数なんて使うのか??」と思ってたところで痛い目を見ました。

問題

引数が渡された場合、「○○最高!!」という文字列を返し、渡されない場合は「Ruby最高!!」という文字列を返すdecideメソッドを定義せよ。
なお、キーワード引数は使用しないこととする。

自分の解法

『aという条件を満たしたらAを、満たさなかったらB、よしif文で瞬殺や!』

『けどどうやって引数が渡された/渡されなかったを判定するんや??』

『う〜ん?引数のsizeが1未満だったら、引数が渡されてないって判定できるのでは?名案キター♪───O(≧∇≦)O────♪』

def decide(*arguments)
	if arguments.size < 1
		return "Ruby最高!!"
	end
	
	arguments.each do |argument|
		if argument.size >= 1
		 return "#{argument}最高!!"
		end
	end
end

puts decide

望ましい解法

デフォルト引数を使うと・・・

def decide(argument = 'Ruby')
	"#{argument}最高!!"
end

puts decide

こんなにコンパクトに書けてしまいます。

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