ruby 返回值_Ruby方法什么也不返回

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

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

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 ,并将grace5 (在调用函数时传递)添加到数组grades的元素中。 因此,当我们使用each迭代器打印成绩时,将显示成绩数组元素的值。

When Methods do not return in ruby

翻译自: https://www.studytonight.com/ruby/methods-contd-in-ruby

ruby 返回值

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值