This tutorial shows how to read and write Java properties files in Ruby.

Ruby provides a gem properties library. The Properties.load() function is used to read the properties file into a ruby object. The properties.store() function is used to write the dictionary to the properties file.

First, Install the properties library in a project using gem install properties command in the terminal.

E:\work\ruby\ruby-examples>gem install properties
Fetching properties-0.2.0.gem
Successfully installed properties-0.2.0
Parsing documentation for properties-0.2.0
Installing ri documentation for properties-0.2.0
Done installing documentation for properties after 1 second
1 gem installed

A new release of RubyGems is available: 3.4.10 → 3.4.22!
Run `gem update --system 3.4.22` to update your installation.

Once the properties gem is installed, you can write a code

Let’s define config.properties

author= Franc
driver= com.mysql.jdbc.Driver
port= 3306
dbname= students
username= root
password= root

How to read Java properties in Ruby

Following are steps to parse properties in Ruby.

  • import properties module using required keyword.
  • use the Properties.load() method that takes the path of a file, returns an iterable dictionary variable
  • Iterate key and values of this using each function
  • Prints the key and value to the console using the puts method

read-properties.rb:

require 'properties'

def read_file(path)
  properties = Properties.load(path)
  return properties
end

path = 'config.properties'
properties = read_file(path)

puts 'Properties Parsr:'
properties.each do |key, value|
  puts "#{key} = #{value}"
end

Running the ruby read-properties.rb in the terminal gives the following output


Write Dictionary ruby object to properties

  • Create and initialize a dictionary of key and value pairs
  • properties.store() function used to write a dictionary object to the properties file, takes the path of a file
  • It creates a properties file with dictionary content.

write-properties.rb:

require 'properties'

def write_file(path, properties)
  properties.store(path, 'Properties Write')
end

path = 'config.properties'
properties = { 'host' => 'localhost', 'username' => 'root', 'password' => 'root', 'dbname' => 'employeedb'  }

write_file(path, properties)

Running the code ruby write-properties.rb on the terminal creates properties and the output is

author= Franc
host=localhost
dbname= employeedb
username= root
password= root