首页 > 解决方案 > 我可以从另一个类中的方法实例化一个类吗?(红宝石)

问题描述

我已经重做了这个问题并包含了两个文件的完整代码。在 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”方法应该创建一个我调用方法的“旅程”变量,例如“完成(站)”或“活动?” 等当我尝试在 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 并试图使帖子更易于阅读。

标签: rubyclassinstantiationirb

解决方案


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

旅程已初始化

它工作正常 - 您是否有一些超出问题范围的问题?


推荐阅读