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

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.

主站蜘蛛池模板: 措勤县| 健康| 临清市| 盐山县| 观塘区| 西宁市| 舒兰市| 西藏| 微山县| 虹口区| 苗栗县| 镇雄县| 无为县| 赞皇县| 凤台县| 察哈| 大姚县| 阜新市| 盈江县| 霸州市| 汝南县| 山西省| 咸丰县| 丰城市| 三明市| 蒙自县| 白山市| 高安市| 洛隆县| 庆安县| 绍兴县| 东源县| 沙坪坝区| 维西| 民权县| 抚州市| 富源县| 察隅县| 阿克陶县| 陇川县| 将乐县|