调用方法时,.map和.times之间的差异。

时间:2021-02-23 22:27:00

I want to call a method multiple times. Both ways below worked but I don´t understand the difference. Can someone clarify it?

我想多次调用一个方法。´下面两方面工作但我不理解的差异。谁能澄清吗?

class Dog
    def bark
        puts 'Wow!'
    end
end

dog = Dog.new
3.times do dog.bark end
3.times.map { dog.bark }

1 个解决方案

#1


5  

map creates a new array containing the values returned by the block.

map创建一个包含块返回值的新数组。

times iterates the given block provided number of times and returns the number of iterations it made. (3 in your case)

times迭代给定块提供的次数,并返回它所做的迭代次数。你的情况(3)

In the following case the return value is 3:

在以下情况下,返回值为3:

val = 3.times do dog.bark end
Wow!
Wow!
Wow!
# => 3
val
# => 3

However when map is used, you would get an array of nil. (because you are not returning anything in your method)

但是当使用map时,会得到一个nil数组。(因为您的方法中没有返回任何内容)

val = 3.times.map { dog.bark }
Wow!
Wow!
Wow!
# => [nil, nil, nil] 
val
# => [nil, nil, nil]

Since your method is intended only to print the output, it does not matter to you what is returned and hence you cannot distinguish between the two.

由于您的方法只打算打印输出,因此返回的内容并不重要,因此您无法区分这两者。

A better way of understanding this is by returning some value from your method. Here:

更好的理解方法是从方法中返回一些值。在这里:

class Dog
    def bark
        1
    end
end

dog = Dog.new

Now you can easily notice the differences as discussed above:

现在您可以很容易地注意到上面讨论的差异:

3.times do dog.bark end
# => 3
3.times.map { dog.bark }
# => [1, 1, 1] 

#1


5  

map creates a new array containing the values returned by the block.

map创建一个包含块返回值的新数组。

times iterates the given block provided number of times and returns the number of iterations it made. (3 in your case)

times迭代给定块提供的次数,并返回它所做的迭代次数。你的情况(3)

In the following case the return value is 3:

在以下情况下,返回值为3:

val = 3.times do dog.bark end
Wow!
Wow!
Wow!
# => 3
val
# => 3

However when map is used, you would get an array of nil. (because you are not returning anything in your method)

但是当使用map时,会得到一个nil数组。(因为您的方法中没有返回任何内容)

val = 3.times.map { dog.bark }
Wow!
Wow!
Wow!
# => [nil, nil, nil] 
val
# => [nil, nil, nil]

Since your method is intended only to print the output, it does not matter to you what is returned and hence you cannot distinguish between the two.

由于您的方法只打算打印输出,因此返回的内容并不重要,因此您无法区分这两者。

A better way of understanding this is by returning some value from your method. Here:

更好的理解方法是从方法中返回一些值。在这里:

class Dog
    def bark
        1
    end
end

dog = Dog.new

Now you can easily notice the differences as discussed above:

现在您可以很容易地注意到上面讨论的差异:

3.times do dog.bark end
# => 3
3.times.map { dog.bark }
# => [1, 1, 1]