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

Method argument code examples

I'm going to start with a very basic example that prints out a user's full name. This is actually a code snippet I took from a real-world code project:

def full_name(first_name, last_name) 
first_name + " " + last_name
end

puts full_name("Jordan", "Hudgens")

As you'll see, this prints out my full name.

The syntax for how to pass arguments to a method is to simply list them off on the same line that you declare the method. From here, you can treat the names that you supplied as arguments (in this case, first_name and last_name) as variables in the method.

Now there is also an alternative syntax that we can use that's quite popular among Ruby developers for passing arguments to methods. Here is a slightly updated version of the code example from earlier:

def full_name first_name, last_name 
first_name + " " + last_name
end

puts full_name"Jordan", "Hudgens"

Notice how all of the parentheses have been taken away? There is some debate on which option is better. I personally prefer to write less code when I have the chance to, so I prefer the second syntax. However both options will work well.

主站蜘蛛池模板: 绵阳市| 买车| 中卫市| 张掖市| 开平市| 贡嘎县| 专栏| 安乡县| 沁阳市| 永嘉县| 大洼县| 颍上县| 荥阳市| 界首市| 平度市| 孟津县| 双城市| 托克托县| 新建县| 唐河县| 津市市| 奉新县| 岳西县| 中超| 江孜县| 广饶县| 体育| 双柏县| 资阳市| 威海市| 石楼县| 茶陵县| 上虞市| 隆昌县| 宁海县| 尼玛县| 长春市| 子长县| 广德县| 泾川县| 侯马市|