ruby - 我可以从另一个类中的方法实例化一个类吗?(红宝石)
问题描述
我已经重做了这个问题并包含了两个文件的完整代码。在 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 并试图使帖子更易于阅读。
解决方案
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
旅程已初始化
它工作正常 - 您是否有一些超出问题范围的问题?
推荐阅读
- node.js - 无法导入三个 dxf 以在 Angular 中查看 dxf 文件
- node.js - 在极光 postgres 无服务器上连接到不同模式时出错
- nginx - Kubernetes GKE ingress-nginx loki grafana prometheus 设置问题
- java - 一对多映射持久化集合
- typescript - 如何将 v-model 与嵌套对象绑定?
- flutter - 使用 Dio download 下载大视频会导致内存不足
- package - 由于需要软件包,无法在 RStudio 中使用 R Markdown
- sql - 用于查找所有不同行的 SQL 查询,这些行的最近日期与单独列中的相同值相关联
- python - 只有当我右键单击并运行文件时,Windows 任务计划程序才会运行
- java - 如何处理 H2 CSVREAD 中的 NULL 值?