Store/Delete a string permanently in Ruby

Can you create a program in ruby that can store a string or delete and
replace them permanently?

Yes I know you can store and change a string that is stored in a
variable by writing

var1 = “Hello world”
puts “The string of var1 is #{var1}, To change var1’s string type in
anything”
var1 = gets.chomp
print “The string has been changed successfully, The string now is
#{var1}”

But whenever you restart the program again the var1’s value changes back
to Hello world. How can you change or the var1’s value or remove it
permanently?

You’d need to write it somewhere as data rather than having it exist
only in volatile memory.
My personal approach is to use the registry for things like program
settings, and text files for changing data. There are plenty of other
options.
Of course, ruby files can modify themselves, and so can Ruby classes.
Perhaps that’s what you were looking for?

On Fri, Apr 26, 2013 at 7:11 AM, cynic limbu [email protected]
wrote:

print “The string has been changed successfully, The string now is
#{var1}”

But whenever you restart the program again the var1’s value changes back
to Hello world. How can you change or the var1’s value or remove it
permanently?

By permanently, do you mean after the program finishes running? What
you are looking for is called “backing store”, such as file systems,
databases and the like were intended for: to enable the persistence of
data across program/script execution. Deciding what type of backing
store to use depends on the program’s needs, the possibilities are
many.

If you are just starting out in this, I guess I’d recommend first
learning how to read and write to a file.

On Fri, Apr 26, 2013 at 2:11 PM, cynic limbu [email protected]
wrote:

print “The string has been changed successfully, The string now is
#{var1}”

But whenever you restart the program again the var1’s value changes back
to Hello world. How can you change or the var1’s value or remove it
permanently?

The most simple way is to store it in a file

$ ls -l data
ls: cannot access data: No such file or directory
$ ./read.rb
“Hello world”
“Hello world .”
$ ./read.rb
“Hello world .”
“Hello world . .”
$ ./read.rb
“Hello world . .”
“Hello world . . .”
$ ls -l data
-rw-r–r–+ 1 Robert None 17 Apr 28 17:41 data
$ cat data
Hello world . . .$ cat -n read.rb
1 #!/usr/bin/ruby
2
3 file_name = ENV[‘HOME’] + “/data”
4
5 var1 = File.read(file_name) rescue “Hello world”
6
7 p var1
8 var1 << " ."
9 p var1
10
11 File.open(file_name, ‘w’) {|io| io.write(var1)}
12

Kind regards

robert