arrays - 范围开头的 * 是什么意思?

标签 arrays ruby range

<分区>

抱歉这个菜鸟问题,这个星号在范围的开头是什么意思?

class Matrix
  def initialize(matrix_string)
    @matrix = matrix_string.split("\n").map do |row|
        row.split.map(&:to_i)
    end
    @rows = rows.length
    @cols = columns.length
  end

  def rows
    @matrix
  end

  def columns
    @matrix.transpose
  end

  # --->>***
  def saddle_points
    [*0...@rows].product([*0...@cols]).select do |coords|
        saddle_point?(*coords)
  end
  # ***<----
end

private
  def   saddle_point?(row, col)
    (@matrix[row][col] == rows[row].max) && 
    (@matrix[row][col] == columns[col].min)
  end
end

最佳答案

如前所述in the documentation :

You can turn an Array into an argument list with * (or splat) operator:

arguments = [1, 2, 3]
my_method(*arguments)

对于 Range 也可以这样做:

arguments = 1..3
my_method(*arguments) # essentially the same as my_method(1, 2, 3)

还允许在数组声明中的范围之前使用 splat 运算符,以将 Range 隐式转换为 Array:

[*1..3]
#⇒ [1, 2, 3]

关于arrays - 范围开头的 * 是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55888413/

相关文章:

php - Foreach 只返回数组元素的第一个字母?

ruby - mac OS X 上 ruby​​ 中的递归 chmod?

function - 在 Excel 中设置范围时 VBA 失败

arrays - PowerShell - 想要了解为什么 $myarr[(-1)..0] 给出 10 1 但 $myarr[$myarr[-1]..0] 给出预期的 10 9 8 ... 0

ruby - 整数数组到范围数组

Python:根据列/行创建具有填充值的数组

C++使用单独的函数按降序对数组进行排序

java - 是否可以在没有两个循环的情况下遍历二维数组?

ruby-on-rails - 如何阻止 Rails Admin 截断字段?

ruby - 如何让 ruby​​-prof 忽略 Ruby 核心/标准库/gem 方法?