Kian Sheik
Kian Sheik

Reputation: 11

Ruby self-editing source code

I am creating a grammar corrector app. You input slang and it returns a formal English correction. All the slang words that are supported are kept inside arrays. I created a method that looks like this for when a slang is entered that is not supported.

def addtodic(lingo)
  print"\nCorrection not supported. Please type a synonym to add '#{lingo}' the dictionary: "
  syn = gets.chomp
  if $hello.include?("#{syn}")
    $hello.unshift(lingo)
    puts"\nCorrection: Hello.\n"
  elsif $howru.include?("#{syn}")
    $howru.unshift(lingo)
    puts"\nCorrection: Hello. How are you?\n"   
  end
end

This works, but only until the application is closed. how can I make this persist so that it amends the source code as well? If I cannot, how would I go about creating an external file that holds all of the cases and referencing that in my source code?

Upvotes: 1

Views: 158

Answers (1)

cyang
cyang

Reputation: 5694

You will want to load and store your arrays in a external file.

How to store arrays in a file in ruby? is relevant to what you are trying to do.

Short example

Suppose you have a file that has one slang phrase per line

% cat hello.txt
hi
hey
yo dawg

The following script will read the file into an array, add a term, then write the array to a file again.

# Read the file ($/ is record separator)
$hello = File.read('hello.txt').split $/

# Add a term
$hello.unshift 'hallo'

# Write file back to original location
open('hello.txt', 'w') { |f| f.puts $hello.join $/ }

The file will now contain an extra line with the term you just added.

% cat hello.txt
hallo
hi
hey
yo dawg

This is just one simple way of storing an array to file. Check the link at the beginning of this answer for other ways (which will work better for less trivial examples).

Upvotes: 3

Related Questions