推荐答案
在 Ruby 中,collect 和 map 是用于对数组或集合中的每个元素进行操作并返回一个新数组的方法。它们的功能完全相同,可以互换使用。
# 示例代码
numbers = [1, 2, 3, 4, 5]
squared_numbers = numbers.map { |num| num ** 2 }
# 或者使用 collect
squared_numbers = numbers.collect { |num| num ** 2 }
puts squared_numbers.inspect
# 输出: [1, 4, 9, 16, 25]本题详细解读
collect 和 map 的基本用法
collect 和 map 方法都是 Enumerable 模块中的方法,它们的作用是对数组或集合中的每个元素执行给定的块(block),并将块的结果收集到一个新的数组中返回。
array = [1, 2, 3, 4]
new_array = array.map { |x| x * 2 }
# new_array 将会是 [2, 4, 6, 8]使用 map 和 collect 的注意事项
- 返回值:
map和collect总是返回一个新的数组,原始数组不会被修改。 - 块的使用:如果块中没有任何操作,
map和collect会返回一个与原数组相同的新数组。 - 性能:
map和collect的性能相同,因为它们实际上是同一个方法的不同名称。
示例代码
// www.javascriptcn.com code example
# 示例 1: 对数组中的每个元素进行平方操作
numbers = [1, 2, 3, 4, 5]
squared_numbers = numbers.map { |num| num ** 2 }
puts squared_numbers.inspect
# 输出: [1, 4, 9, 16, 25]
# 示例 2: 对数组中的每个元素进行字符串转换
words = ["apple", "banana", "cherry"]
capitalized_words = words.collect { |word| word.capitalize }
puts capitalized_words.inspect
# 输出: ["Apple", "Banana", "Cherry"]总结
collect 和 map 是 Ruby 中非常常用的方法,用于对数组或集合中的每个元素进行操作并返回一个新的数组。它们的功能完全相同,可以互换使用。