3: Methods 方法
In short, all methods are, are shortcuts of longer bits of code. To get straight into creating your own method, methods are created by writing the def keyword (as in “define”) followed by the name you want to give your method, and then closed with end, just like with if-statements.
简单的说,方法就是一段代码的快捷方式。
当你想要在多个地方运行相同的代码的时候,你实际上并不需要在每个地方都复制粘贴上那一段代码,而是你可以为那一段代码写一个方法,只需要复制粘贴这个方法就好了。
因为这个方法是这段代码的快捷方式,所以当你运行这个方法的时候,就相当于是运行了这一段代码。
除了可以减少代码的行数之外,使用方法还可以让你更加方便的修改代码。
比如说,在你写好代码之后你想要修改,如果你没有使用方法的话,你需要在每一个你复制粘贴的地方都进行修改,而如果你使用了方法的话,你就只需要在方法里修改就好了。
你可以使用def xxx这样的格式来新定义一个方法,其中def就是define(定义)的简写,xxx就是你的方法名,我们来看下面这个例子:
In this example, we’ve created a new method called my_method, which prints out "Printing from my_method!". We then close that method with end and call/run/execute the code inside that method by simply writing down the name of that method, my_method.
在上面的例子中,我们新写了,或者说创建了,或者说定义了一个新的方法,这个方法的名字叫做my_method(我的方法),同时也可以发现,定义方法也和if条件句一样,你需要在结尾使用end。
额外补充,定义方法其实也和if条件句一样,并不是一定需要end,在某些情况下是可以省略end的,就比如说例子的这种情况就是可以省略end的,但是,我还是希望你和记if-end对一样,定义方法记def-end对。
接着,我们运行了my_method这个方法,这个方法会打印出“Printing from my_method!”(来自我的方法的打印)。
也就是说此时,不管你运行my_method,还是运行print "Printing from my_method!",它们的结果是一样的,因为my_method这个方法就是print "Printing from my_method!"。
In various other languages, to call a method you have to follow the method name with (). In Ruby, those parentheses are optional. They make it an explicit call; more on this near the end of this tutorial.
In short, all methods are, are shortcuts of longer bits of code. To get straight into creating your own method, methods are created by writing the def keyword (as in “define”) followed by the name you want to give your method, and then closed with end, just like with if-statements.
简单的说,方法就是一段代码的快捷方式。
当你想要在多个地方运行相同的代码的时候,你实际上并不需要在每个地方都复制粘贴上那一段代码,而是你可以为那一段代码写一个方法,只需要复制粘贴这个方法就好了。
因为这个方法是这段代码的快捷方式,所以当你运行这个方法的时候,就相当于是运行了这一段代码。
除了可以减少代码的行数之外,使用方法还可以让你更加方便的修改代码。
比如说,在你写好代码之后你想要修改,如果你没有使用方法的话,你需要在每一个你复制粘贴的地方都进行修改,而如果你使用了方法的话,你就只需要在方法里修改就好了。
你可以使用def xxx这样的格式来新定义一个方法,其中def就是define(定义)的简写,xxx就是你的方法名,我们来看下面这个例子:
In this example, we’ve created a new method called my_method, which prints out "Printing from my_method!". We then close that method with end and call/run/execute the code inside that method by simply writing down the name of that method, my_method.
在上面的例子中,我们新写了,或者说创建了,或者说定义了一个新的方法,这个方法的名字叫做my_method(我的方法),同时也可以发现,定义方法也和if条件句一样,你需要在结尾使用end。
额外补充,定义方法其实也和if条件句一样,并不是一定需要end,在某些情况下是可以省略end的,就比如说例子的这种情况就是可以省略end的,但是,我还是希望你和记if-end对一样,定义方法记def-end对。
接着,我们运行了my_method这个方法,这个方法会打印出“Printing from my_method!”(来自我的方法的打印)。
也就是说此时,不管你运行my_method,还是运行print "Printing from my_method!",它们的结果是一样的,因为my_method这个方法就是print "Printing from my_method!"。
In various other languages, to call a method you have to follow the method name with (). In Ruby, those parentheses are optional. They make it an explicit call; more on this near the end of this tutorial.