Ruby 中的“map”方法有什么作用?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12084507/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 05:21:50  来源:igfitidea点击:

What does the "map" method do in Ruby?

rubymaprangeenumeration

提问by bigpotato

I'm new to programming. Can someone explain what .mapwould do in:

我是编程新手。有人可以解释一下.map会做什么:

params = (0...param_count).map

回答by Danil Speransky

The mapmethod takes an enumerable object and a block, and runs the block for each element, outputting each returned value from the block (the original object is unchanged unless you use map!):

map方法接受一个可枚举对象和一个块,并为每个元素运行该块,输出该块的每个返回值(原始对象不变,除非您使用map!)

[1, 2, 3].map { |n| n * n } #=> [1, 4, 9]

Arrayand Rangeare enumerable types. mapwith a block returns an Array. map!mutates the original array.

Array并且Range是可枚举类型。map带有块返回一个数组。 map!改变原始数组。

Where is this helpful, and what is the difference between map!and each? Here is an example:

这哪里是有帮助的,是什么样的区别map!each?下面是一个例子:

names = ['danil', 'edmund']

# here we map one array to another, convert each element by some rule
names.map! {|name| name.capitalize } # now names contains ['Danil', 'Edmund']

names.each { |name| puts name + ' is a programmer' } # here we just do something with each element

The output:

输出:

Danil is a programmer
Edmund is a programmer

回答by boulder_ruby

map, along with selectand eachis one of Ruby's workhorses in my code.

map,selecteach是我代码中 Ruby 的主力之一。

It allows you to run an operation on each of your array's objects and return them all in the same place. An example would be to increment an array of numbers by one:

它允许您对数组的每个对象运行操作并将它们全部返回到同一位置。一个例子是将数字数组加一:

[1,2,3].map {|x| x + 1 }
#=> [2,3,4]

If you can run a single method on your array's elements you can do it in a shorthand-style like so:

如果您可以在数组元素上运行单个方法,则可以像这样以速记方式进行操作:

  1. To do this with the above example you'd have to do something like this

    class Numeric
      def plusone
        self + 1
      end
    end
    [1,2,3].map(&:plusone)
    #=> [2,3,4]
    
  2. To more simply use the ampersand shortcut technique, let's use a different example:

    ["vanessa", "david", "thomas"].map(&:upcase)
    #=> ["VANESSA", "DAVID", "THOMAS"]
    
  1. 要使用上面的示例执行此操作,您必须执行以下操作

    class Numeric
      def plusone
        self + 1
      end
    end
    [1,2,3].map(&:plusone)
    #=> [2,3,4]
    
  2. 为了更简单地使用与号快捷键技术,让我们使用一个不同的例子:

    ["vanessa", "david", "thomas"].map(&:upcase)
    #=> ["VANESSA", "DAVID", "THOMAS"]
    

Transforming data in Ruby often involves a cascade of mapoperations. Study map& select, they are some of the most useful Ruby methods in the primary library. They're just as important as each.

在 Ruby 中转换数据通常涉及级联map操作。Study map& select,它们是主要库中一些最有用的 Ruby 方法。它们和each.

(mapis also an alias for collect. Use whatever works best for you conceptually.)

map也是 的别名collect。从概念上使用最适合您的方法。)

More helpful information:

更多有用信息:

If the Enumerableobject you're running eachor mapon contains a set of Enumerable elements (hashes, arrays), you can declare each of those elements inside your block pipes like so:

如果您正在运行或运行的Enumerable对象包含一组 Enumerable 元素(散列、数组),您可以像这样在块管道中声明这些元素中的每一个:eachmap

[["audi", "black", 2008], ["bmw", "red", 2014]].each do |make, color, year|
  puts "make: #{make}, color: #{color}, year: #{year}"
end
# Output:
# make: audi, color: black, year: 2008
# make: bmw, color: red, year: 2014

In the case of a Hash (also an Enumerableobject, a Hash is simply an array of tuples with special instructions for the interpreter). The first "pipe parameter" is the key, the second is the value.

在哈希的情况下(也是一个Enumerable对象,哈希只是一个带有解释器特殊指令的元组数组)。第一个“管道参数”是键,第二个是值。

{:make => "audi", :color => "black", :year => 2008}.each do |k,v|
    puts "#{k} is #{v}"
end
#make is audi
#color is black
#year is 2008

To answer the actual question:

要回答实际问题:

Assuming that paramsis a hash, this would be the best way to map through it: Use two block parameters instead of one to capture the key & value pair for each interpreted tuple in the hash.

假设这params是一个散列,这将是映射它的最佳方法:使用两个块参数而不是一个来捕获散列中每个解释元组的键值对。

params = {"one" => 1, "two" => 2, "three" => 3}
params.each do |k,v|
  puts "#{k}=#{v}"
end
# one=1
# two=2
# three=3

回答by tokhi

Using ruby 2.4 you can do the same thing using transform_values, this feature extracted from rails to ruby.

使用 ruby​​ 2.4 你可以使用 做同样的事情transform_values,这个特性从 rails 提取到 ruby​​。

h = {a: 1, b: 2, c: 3}

h.transform_values { |v| v * 10 }
 #=> {a: 10, b: 20, c: 30}

回答by Pedro Nascimento

0..param_countmeans "up to and including param_count". 0...param_countmeans "up to, but not including param_count".

0..param_count表示“最多并包括 param_count”。 0...param_count表示“最多但不包括 param_count”。

Range#mapdoes not return an Enumerable, it actually maps it to an array. It's the same as Range#to_a.

Range#map不返回 an Enumerable,它实际上将它映射到一个数组。它与Range#to_a.

回答by Ry-

It "maps" a function to each item in an Enumerable- in this case, a range. So it would call the block passed once for every integer from 0 to param_count(exclusive - you're right about the dots) and return an array containing each return value.

它将函数“映射”到范围中的每个项目Enumerable- 在这种情况下,是一个范围。因此,它会为从 0 到param_count(不包括 - 您对点的说法是正确的)的每个整数调用一次传递的块,并返回一个包含每个返回值的数组。

Here's the documentation for Enumerable#map.It also has an alias, collect.

这是Enumerable#map. 它还有一个别名,collect.

回答by gkstr1

Map is a part of the enumerable module. Very similar to "collect" For Example:

Map 是 enumerable 模块的一部分。非常类似于“收集”例如:

  Class Car

    attr_accessor :name, :model, :year

    Def initialize (make, model, year)
      @make, @model, @year = make, model, year
    end

  end

  list = []
  list << Car.new("Honda", "Accord", 2016)
  list << Car.new("Toyota", "Camry", 2015)
  list << Car.new("Nissan", "Altima", 2014)

  p list.map {|p| p.model}

Map provides values iterating through an array that are returned by the block parameters.

Map 提供遍历由块参数返回的数组的值。

回答by Jivan Pal

#each

#each

#eachruns a function for each element in an array. The following two code excerpts are equivalent:

#each为数组中的每个元素运行一个函数。以下两个代码摘录是等效的:

x = 10
["zero", "one", "two"].each{|element|
    x++
    puts element
}
x = 10
array = ["zero", "one", "two"]

for i in 0..2
    x++
    puts array[i]
end

#map

#map

#mapapplies a function to each element of an array, returning the resulting array. The following are equivalent:

#map将函数应用于数组的每个元素,返回结果数组。以下是等效的:

array = ["zero", "one", "two"]
newArray = array.map{|element| element.capitalize()}
array = ["zero", "one", "two"]

newArray = []
array.each{|element|
    newArray << element.capitalize()
}

#map!

#map!

#map!is like #map, but modifies the array in place. The following are equivalent:

#map!就像#map,但在适当的位置修改数组。以下是等效的:

array = ["zero", "one", "two"]
array.map!{|element| element.capitalize()}
array = ["zero", "one", "two"]
array = array.map{|element| element.capitalize()}