ruby 返回值
Methods may or may not return value. There is no rule that they must return the value. These kind of methods can be used to display some type of message.
方法可能会也可能不会返回值。 没有规则要求它们必须返回值。 这些方法可用于显示某种类型的消息。
![When Methods do not return in ruby](https://i-blog.csdnimg.cn/blog_migrate/68d4619a8f42ec0551cc60a022537a3c.png)
Here is a method called prompt
that displays a message that is passed to it. We can use this method to display short messages to abstract the code from main program. We call this method by passing "Hello, World\n" and it displays the message.
这是一种称为prompt
的方法,该方法显示传递给它的消息。 我们可以使用此方法显示短消息,以从主程序中提取代码。 我们通过传递“ Hello,World \ n”来调用此方法,并显示消息。
We get input from the user and store it in the variable value
and we call the function prompt by passing the variable value to display the message entered by the user. This method does not return anything.
我们从用户那里获取输入并将其存储在变量value
并通过传递变量值以显示用户输入的消息来调用函数提示。 此方法不返回任何内容。
Ruby方法:使用数据结构 (Ruby Method: Working with Data Structure)
Another reason to use a method that doesn't return a value is when you want to create a method that might have to return multiple values or when you have to operate on larger data structure within the method.
使用不返回值的方法的另一个原因是,当您想创建一个可能必须返回多个值的方法时,或者当您必须对方法中的较大数据结构进行操作时。
![When Methods do not return in ruby](https://i-blog.csdnimg.cn/blog_migrate/00d96f35b81462203945023455340f37.png)
In this method, we have declared and initialized the array called grade
. We have defined a method named points
, which adds the value specified by the user to each element of the array. This method takes
array and
another variable.
在此方法中,我们声明并初始化了称为grade
的数组。 我们定义了一个名为points
的方法,该方法将用户指定的值添加到数组的每个元素中。 该方法需要
数组和
另一个变量 。
arr.map! { |grade| grade+= grace }
This statement uses a method called map
. Map method belongs to the class array. Map method takes each element out of the array and stores it in some variable, using that variable we can perform our desired operations.
该语句使用一种称为map
的方法。 Map方法属于类数组 。 Map方法将每个元素移出数组并将其存储在某个变量中,使用该变量我们可以执行所需的操作。
Here, for every instance, it stores the element of the array in the variable grade
and adds the value grace
to it. For first iteration, 60 is stored in grade
and the value of grace
which is 5 (passed while calling function) is added to the element of the array grades
. So, when we print the grades using each
iterator, the value of the elements of grades array is displayed.
在这里,对于每个实例,它都将数组的元素存储在变量grade
并为其添加值grace
。 对于第一次迭代,将60存储在grade
,并将grace
值5 (在调用函数时传递)添加到数组grades
的元素中。 因此,当我们使用each
迭代器打印成绩时,将显示成绩数组元素的值。
![When Methods do not return in ruby](https://i-blog.csdnimg.cn/blog_migrate/b073f310fb11000ecbb3a4b6826efc23.png)
翻译自: https://www.studytonight.com/ruby/methods-contd-in-ruby
ruby 返回值