TheMightyNight
TheMightyNight

Reputation: 159

Ruby - Parse a file into hash

I've a file containing hundreds of object and value combination like below manner. I want to get input from user as object name & numeric value and return that associated value.

Object  cefcFRUPowerOperStatus
Type    PowerOperType 
        1:offEnvOther
        2:on
        3:offAdmin
        4:offDenied
        5:offEnvPower
        6:offEnvTemp

Object  cefcModuleOperStatus
Type    ModuleOperType 
        1:unknown
        2:ok
        3:disabled
        4:okButDiagFailed
        5:boot
        6:selfTest

E.g. - input -

           objectName = 'cefcModuleOperStatus'

           TypeNumber = '4'

Return - 'okButDiagFailed'

I am not aware of Ruby and get this done to help my peer. So please excuse if this is a novice question.

Note:- I've to create the file so with any file format it would be a great help.

Upvotes: 1

Views: 851

Answers (1)

Shaunak
Shaunak

Reputation: 18018

If like you say you have control over creating the original data file, then creating it in json format would make accessing it trivial.

Here is a repl.it of complete working example. Just select the main.rb file and hit run!

For example if you create json file like:

data.json

{
  "cefcFRUPowerOperStatus": {
    "type": "PowerOperType",
    "status": {
      "1": "offEnvOther",
      "2": "on",
      "3": "offAdmin",
      "4": "offDenied",
      "5": "offEnvPower",
      "6": "offEnvTemp"
    }
  },
  "cefcModuleOperStatus": {
    "type": "ModuleOperType",
    "status": {
      "1": "unknown",
      "2": "ok",
      "3": "disabled",
      "4": "okButDiagFailed",
      "5": "boot",
      "6": "selfTest"
    }
  }
}

Then parsing it and accessing it in Ruby is as simple as :

require 'json'
file = File.read('data.json')
data = JSON.parse(file)

#accessing this data is simple now:

puts data["cefcModuleOperStatus"]["status"]["4"]
# > okButDiagFailed

Note: that this JSON format will work if your statuses are unique. If they are not, you can still use this way, but you will need to convert JSON to an array format. Let me know if this is the case and I can show you how to modify the json and ruby code for this.

Hope that helps, let me know if you have further questions about how this works.

Upvotes: 5

Related Questions