gpt4 book ai didi

ruby-on-rails - Ruby - 哈希数组 - 未定义的方法 'each' 错误

转载 作者:太空宇宙 更新时间:2023-11-03 17:14:21 25 4
gpt4 key购买 nike

我想遍历哈希数组并将值打印到终端。

当前收到错误:

main.rb:14:in `print': undefined method `each' for nil:NilClass (NoMethodError)
from main.rb:22:in `<main>'

我想要遍历,而不是像puts @transactions这样简单的东西>

我收到此错误的任何想法?谢谢

class TestRun
@transactions = [
{:repayment_number => 1, :repayment_amount => 224.34},
{:repayment_number => 2, :repayment_amount => 241.50},
{:repayment_number => 3, :repayment_amount => 135.04},
{:repayment_number => 4, :repayment_amount => 91.00}
]

def print()
@transactions.each do |t|
puts "#{t[:repayment_number]} - #{t[:repayment_amount]}"
end
end

end

@test = TestRun.new
@test.print()

最佳答案

您已经定义了两次 @transactions,最初是当 self 等于 TestRun 时,使其成为一个类实例变量 ,然后在 print 方法中,当 self 是实例 TestRun.new 时,使它成为一个实例变量 .这两个变量与 @night@day 一样不同。

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

使print成为类方法

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 = #<TestRun:0x007fcccb13f390>
# 1 - 224.34
# 2 - 241.5

在初始化方法中定义@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 = #<TestRun:0x007fcccb2ae988>
# self within print = #<TestRun:0x007fcccb2ae988>
# 1 - 224.34
# 2 - 241.5

关于ruby-on-rails - Ruby - 哈希数组 - 未定义的方法 'each' 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41799205/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com