Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby 实施:方法与自定义方法_Ruby - Fatal编程技术网

Ruby 实施:方法与自定义方法

Ruby 实施:方法与自定义方法,ruby,Ruby,我已经读过了,但是在那里我很难实现这些概念 我正在做一个来自exercism.io的练习,它提供了测试。本练习的目的是实现一个累加方法,返回传递给它的数字的平方。我们需要在不使用map/inject的情况下执行此操作 这没有问题,但其中一项测试如下: def test_accumulate_upcases result = %w(hello world).accumulate(&:upcase) assert_equal %w(HELLO WORLD), result

我已经读过了,但是在那里我很难实现这些概念

我正在做一个来自exercism.io的练习,它提供了测试。本练习的目的是实现一个累加方法,返回传递给它的数字的平方。我们需要在不使用map/inject的情况下执行此操作

这没有问题,但其中一项测试如下:

  def test_accumulate_upcases
    result = %w(hello world).accumulate(&:upcase)
    assert_equal %w(HELLO WORLD), result
  end
我有以下课程

class Array

  def accumulate
    squares = []
    self.each { |x| squares << x**2 unless x.is_a? String }

    squares
  end

  def upcase
    upcase = []
    self.each { |word| word.upcase }

    upcase
  end
end
类数组
def累积
正方形=[]

self.each{x | squares
accumulate
方法希望收到一个名为
Symbol
的方法名

def accumulate meth = nil
  result = []
  case 
  when meth.nil?
    self.each { |e| result << e.public_send meth }
  when block_given?
    self.each { |e| result << yield e }
  else
    fail 'This method expects either block or method name'
  end
end
def累计meth=nil
结果=[]
案例
什么时候服用冰毒?

self.each{e | result似乎希望您使用新方法
acculate
扩展
Array
类,该方法将在数组的每个元素上累积调用给定
proc
的结果

一个实现可以如下所示:

class Array
    def accumulate(&block) 
        self.collect { |i| block.yield(i) }
    end
end

p result = %w(hello world).accumulate(&:upcase)  # Prints ["HELLO", "WORLD"]
p result = %w(hello world).accumulate { |b| b.upcase } # Prints ["HELLO", "WORLD"]
请注意,
%w(HELLO WORLD)
与array
[“HELLO”,“WORLD”]


关于中的
&
运算符的用法有一个很好的解释-请阅读一元数部分&

谢谢,这很有意义。如果你不介意的话,什么是
public\u send
谢谢@SergioTulentsev-这是很有用的信息!这很好用!尽管我使用了
每个
ins而不是
collect
,因为练习需要我们手动累积结果。同时感谢您提供的链接!您只需传递块,即
collect(&block)