当前位置:  开发笔记 > 编程语言 > 正文

Ruby - 哈希数组 - 未定义的方法'每个'错误

如何解决《Ruby-哈希数组-未定义的方法'每个'错误》经验,为你挑选了1个好方法。



1> Cary Swovela..:

你定义了@transactions两次,最初是self等于TestRun,使它成为一个类实例变量,然后在print方法中,什么时候self是实例TestRun.new,使那一个成为一个实例变量.这两个变量是根据不同的@night@day.

以下是使代码工作的三种方法(前两种仅用于教育目的).

使打印成为一种类方法

class TestRun
  puts "self at class level = #{self}"
  @transactions = [
    {:repayment_number => 1, :repayment_amount => 224.34},
    {:repayment_number => 2, :repayment_amount => 241.50}
  ]
  def self.print
    puts "self within self.print = #{self}"
    @transactions.each do |t|
      puts "#{t[:repayment_number]} - #{t[:repayment_amount]}"
    end
  end
end
  #=> self at class level = TestRun
TestRun.print
  #=> self within self.print = TestRun
  #   1 - 224.34
  #   2 - 241.5

从方法print中访问类实例变量

class TestRun
  @transactions = [
    {:repayment_number => 1, :repayment_amount => 224.34},
    {:repayment_number => 2, :repayment_amount => 241.50}
  ]
  def print
    puts "self within print = #{self}"
    self.class.instance_variable_get(:@transactions).each do |t|
      puts "#{t[:repayment_number]} - #{t[:repayment_amount]}"
    end
  end
end

TestRun.new.print
  #=> self within print = #
  #   1 - 224.34
  #   2 - 241.5

在initialize方法中定义@transactions,使其成为实例变量

这就是@ 31piy所做的,也很可能是OP的目的.

class TestRun
  def initialize
    puts "self within initialize = #{self}"    
    @transactions = [
      {:repayment_number => 1, :repayment_amount => 224.34},
      {:repayment_number => 2, :repayment_amount => 241.50}
    ]
  end
  def print
    puts "self within print = #{self}"
    @transactions.each do |t|
      puts "#{t[:repayment_number]} - #{t[:repayment_amount]}"
    end
  end
end

TestRun.new.print
  #=> self within initialize = #
  #   self within print = #
  #   1 - 224.34
  #   2 - 241.5

推荐阅读
小白也坚强_177
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有