官术网_书友最值得收藏!

Creating methods in Ruby

Methods are a powerful feature for building Ruby programs. They allow you to encapsulate behavior and call the method later on to build the functionality of programs. This is an important section, as you are going to learn about methods in Ruby.

Before we walk through the syntax guide, I want to show you a real-world Rails application code file called the jobs_controller.rb:

Each one of the items, such as index, show, edit, and create, are methods. As you may notice, there are many methods in a file, and each of them performs a specific task, behavior, or action. You are going to be using these methods day in and day out as a Ruby developer, so it's important you have a firm grasp on what the concept is.

Methods have a specific syntax. They begin with the def word followed by the name of your method. In general, your method name should reflect its functionality or behavior for easy readability. Also, all the words should be in lowercase and snake case (words joined by an underscore). For example, if I want to create a method that lists out baseball teams, then I would name my method something like this:

def baseball_team_list 
end

Also, methods always end with the end word. Your logic goes into the area between the name and the end parts of the method. Consider this example:

def baseball_team_list 
p ["A's", "Angels", "Astros"]
end

To access this method, I can simply call the method by its name:

baseball_team_list 

The logic inside the method will get executed:

If you run this code without making the call, it will show you that a method called baseball_team_list exists with the baseball_team_list output:

When you simply run a method, the logic inside it does not get executed. If you want to execute the logic, you have to explicitly call the method.

So, this is how you create and access methods in Ruby.

主站蜘蛛池模板: 宽甸| 山丹县| 永康市| 武清区| 新田县| 鞍山市| 阿拉尔市| 若尔盖县| 汉川市| 论坛| 甘泉县| 沛县| 大连市| 中山市| 巫山县| 玉溪市| 河津市| 布尔津县| 芜湖县| 石楼县| 田林县| 库伦旗| 灵石县| 壤塘县| 达尔| 聂拉木县| 云梦县| 克拉玛依市| 凭祥市| 牙克石市| 任丘市| 青海省| 邮箱| 曲松县| 天峨县| 铁力市| 萨嘎县| 常德市| 多伦县| 怀集县| 通化市|