- Comprehensive Ruby Programming
- Jordan Hudgens
- 325字
- 2021-07-02 21:13:30
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:

So, this is how you create and access methods in Ruby.
- PHP動態(tài)網(wǎng)站程序設(shè)計
- 小程序?qū)崙?zhàn)視頻課:微信小程序開發(fā)全案精講
- Servlet/JSP深入詳解
- AngularJS深度剖析與最佳實踐
- 編譯系統(tǒng)透視:圖解編譯原理
- PLC編程及應(yīng)用實戰(zhàn)
- Android系統(tǒng)級深入開發(fā)
- Nginx Lua開發(fā)實戰(zhàn)
- Android應(yīng)用案例開發(fā)大全(第二版)
- 軟件測試實用教程
- Visual Basic程序設(shè)計習(xí)題與上機實踐
- Maker基地嘉年華:玩轉(zhuǎn)樂動魔盒學(xué)Scratch
- Scala編程實戰(zhàn)
- Struts 2.x權(quán)威指南
- Python數(shù)據(jù)科學(xué)實踐指南