如何在Ruby文件之间传递数组

时间:2016-02-04 21:13:26

标签: arrays ruby printing parameter-passing

我想将一个数组从一个Ruby文件传递给另一个。

我有三个文件:

  • main.rb的
  • company.rb
  • applicant.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

最后是applicant.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文件以从中获取一些信息。每当我尝试打印发送给申请人文件的值时,都不打印任何内容。

2 个答案:

答案 0 :(得分:0)

您无法将数组从ruby文件传递到另一个。,您只能在类和对象之间传递数据。

其他可能有用的可能性:

  • 常量(用起始大写字母定义)
  • 全局变量(以$开头)
  • 单身

要将数据保存在类实例(对象)中,您需要属性(以@开头的变量)。

你可以在ruby的每本初学者手册中找到这个概念(如果没有,那么手册不值得使用)

你做了另一个common error

让我们用一个小例子来检查它:

class Company
  attr_accessor :jobs
  def initialize()
    jobs='This should be assigned to my accessor jobs'
  end
end

puts Company.new.jobs

结果是一个空行。

发生什么事了?在initialize - 方法中,您可以定义局部变量jobs。本地意味着,它仅在方法中可用时,方法离开时会丢失。

正确的是1)使用实例变量:

class Company
  attr_accessor :jobs
  def initialize()
    @jobs='This should be assigned to my accessor jobs'
  end
end

或2)使用访问器方法:

class Company
  attr_accessor :jobs
  def initialize()
    self.jobs='This should be assigned to my accessor jobs'
  end
end

在这两种情况下,puts Company.new.jobs都会返回您定义的文本。

另见Ruby instance variable access

答案 1 :(得分:0)

如果我正确读到这个,你要求ruby进行计算,但从不说明它应该被打印出来。我相信将main.rb的最后一行更改为:

puts company.find_applicants('google')

应该足够了。