我可以从另一个类中的方法实例化一个类吗? (Ruby)[关闭]

问题描述 投票:-1回答:1

我已经重做了问题,并包含了两个文件的完整代码。在touch_in方法中,我试图在名为“ journey”的变量中实例化Journey类。

require_relative 'journey'

class Oystercard

  MAXIMUM_BALANCE = 90

  MINIMUM_BALANCE = 1

  MINIMUM_CHARGE = 1

  def initialize
    @balance = 0
    @journeys = {}
  end

  def top_up(amount)
    fail 'Maximum balance of #{maximum_balance} exceeded' if amount + balance > MAXIMUM_BALANCE
    @balance += amount
  end

  def in_journey?
    @in_journey
  end

  def touch_out(station)
    deduct(MINIMUM_CHARGE)
    @exit_station = station
    @in_journey = false
    @journeys.merge!(entry_station => exit_station)
  end

  def touch_in(station)
    fail "Insufficient balance to touch in" if balance < MINIMUM_BALANCE
    journey = Journey.new
    @in_journey = true
    @entry_station = station
  end

  attr_reader :journeys

  attr_reader :balance

  attr_reader :entry_station

  attr_reader :exit_station

  private

  def deduct(amount)
    @balance -= amount
  end

end

旅程文件如下:

    class Journey

  PENALTY_FARE = 6

  MINIMUM_CHARGE = 1

  def initialize(station = "No entry station")
    @previous_journeys = {}
  end

  def active?
    @active
  end

  def begin(station = "No entry station")
    @active = true
    @fare = PENALTY_FARE
    @entry_station = station
  end

  def finish(station = "No exit station")
    @active = false
    @fare = MINIMUM_CHARGE
    @exit_station = station
    @previous_journeys.merge!(entry_station => exit_station)
  end

attr_reader :fare

attr_reader :previous_journeys

attr_reader :entry_station

attr_reader :exit_station

end

我认为'touch_in'方法应该创建一个'旅程'变量,我在上面调用了这些方法,例如'finish(station)'或'active?'。等等。当我尝试在IRB中执行此操作时,出现以下错误:

2.6.3 :007 > journey
Traceback (most recent call last):
        4: from /Users/jamesmac/.rvm/rubies/ruby-2.6.3/bin/irb:23:in `<main>'
        3: from /Users/jamesmac/.rvm/rubies/ruby-2.6.3/bin/irb:23:in `load'
        2: from /Users/jamesmac/.rvm/rubies/ruby-2.6.3/lib/ruby/gems/2.6.0/gems/irb-1.0.0/exe/irb:11:in `<top (required)>'
        1: from (irb):7
NameError (undefined local variable or method `journey' for main:Object)

我知道上面的许多代码都是草率编写的,除了“旅途”问题外,可能还有其他地方,这是错误的。如果是这种情况,请告诉我越多越好。

对任何试图在我的第一次尝试中帮助我的人表示歉意,正如我说的那样,我仍然习惯于SO,并试图使文章更易于阅读。

ruby class instantiation irb
1个回答
1
投票
class Journey
    # ...
    def initialize
        puts "Journey initialized"
      # ...
    end
    # ...
  end


require_relative 'journey'

class Oystercard

    def initialize
    end
    # ...
    def touch_in(station)
      journey = Journey.new
      # ...
    end
  end

  Oystercard.new.touch_in("station")

stack_question $ ruby​​ oystercard.rb

旅程已初始化

效果很好-您对此是否有超出问题范围的问题?

© www.soinside.com 2019 - 2024. All rights reserved.