【发布时间】:2016-02-04 21:13:25
【问题描述】:
我想将一个数组从一个 Ruby 文件传递给另一个文件。
我有三个文件:
- main.rb
- company.rb
- 申请者.rb
这是 main.rb 的代码:
require './src/company.rb'
require './src/applicant.rb'
company = Company.new('data/boundless.json')
company.find_applicants('google')
这是 company.rb 的代码:
require 'json'
require_relative 'applicant.rb'
class Company
attr_accessor :jobs , :arrOfApp
def self.load_json(filepath)
file = File.read(filepath)
return JSON.parse(file)
end
def initialize(filePath)
# Load the json file and loop over the jobs to create an array of instance of `Job`
# Assign the `jobs` instance variable.
jobs=Array.new
data_hash = Company.load_json(filePath)
numberOfJobs= data_hash['jobs'].length
for i in 0 ... numberOfJobs
jobs[i]=data_hash['jobs'][i]['applicants']
# puts jobs
end
end
## TODO: Impelement this method to return applicants from all jobs with a
## tag matching this keyword
def find_applicants(keyWord)
app =Applicant.new
arrOfApp=Array.new
app.data_of_applicant(jobs)
end
end
最后是申请者.rb 的代码:
require_relative 'company.rb'
class Applicant
attr_accessor :id, :name, :tags
def initialize
end
def data_of_applicant(j)
id=Array.new
name=Array.new
tags=Array.new
puts j
end
end
程序读取一个 JSON 文件以从中获取一些信息。每当我尝试打印发送到申请人文件的值时,都不会打印任何内容。
【问题讨论】:
-
我建议使用小型数据库,可能是 SQLite,它充当数据的公共存储库。 Sequel 是一个很棒的 ORM,使它易于使用。或者,您可以使用 YAML 文件,但这不是 YAML 的良好用途,因为如果在读/写期间发生冲突,一个文件对文件的更改可能会对另一个文件造成严重破坏。您还可以通过管道将文件放在一起并在它们之间传递数据。一般来说,您需要正确格式化您的代码。它可以帮助您调试,也可以帮助我们帮助您。 Ruby 变量在 snake_case 中,而不是 camelCase
-
我没有看到您尝试重写数据文件的代码。不要让我们为你写。我们很乐意帮助您调试问题,但请向我们展示您在这方面所做的努力。
-
@theTinMan 我不是要你写任何东西,我只是问为什么它不传递数据,就是这样
-
它没有传递任何东西,因为你没有告诉它。
-
我已将申请人文件包含在公司文件中,并从我已经从他们那里调用的方法 data_of_applicant 中调用了方法 data_of_applicant
标签: arrays ruby printing parameter-passing