Help us understand the problem. What is going on with this article?

【Ruby】Ruby入門:関数的メソッドを作ってみよう

More than 3 years have passed since last update.

やること

関数的メソッドを理解する。

記録

関数的メソッドをググったら、「関数的メソッドとはレシーバがないメソッドのこと」という説明があったけど、よくわからないので例で見てみます。

メソッドを定義してそれを呼び出す場合、定義するにはdefの後に関数名を書きます。

hello.rb
def sayHi()
  puts "hello!"
end

sayHi()

実行結果

hello!

メソッドにはdef sayHi(name)のようにオプションを付けることもできます。

hello.rb
def sayHi(name)
  puts "hello! " + name
end

sayHi("Tom")
sayHi("Bob")

実行結果

hello! Tom
hello! Bob

引数には初期値を設定することもできます。def sayHi(name = "Steve")とすると、nameが設定されていない時は"Steve"を使ってくれます。

hello.rb
def sayHi(name = "Steve")
  puts "hello! " + name
end

sayHi("Tom")
sayHi("Bob")
sayHi()

実行結果

hello! Tom
hello! Bob
hello! Steve

難しくなってきたぞー。

Mocacamo
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした