27 February 2010

Some Ruby Code Snippets For Fun!

Aah Well, I see that I have not written anything here for quite a while in the month of February.
The reason I must say is in this month I haven't touched anything special to pen it down. But the eager to write down something , is the result you see this post coming up.

You would enjoy this only if you are a Ruby enthusiast or a hardcore programming freak.

Nothing special, a few Ruby tips to share :)

Tip #1

You have a ruby program which you run though command, see the result in command and have a feel that, you would want the output to be saved in your computer in some text files. Here is what you can do while executing the program

ruby test_program.rb > output.txt

Tip #2
Using YAML to write string into a file and then load the same file.

About YAML:
YAML is a format for representing objects as strings. You can use other formats, but YAML is nice because it’s human-readable (and human-editable) as well as computer-readable.
YAML is not actually part of the Ruby core, but it is part of the standard distribution.When you install Ruby, you install YAML, too. But if you want to actually use YAML, you’ll need to import it into your program. This is really easy, with the require method:
Here is the code snippet which will create a text file and save the string:

require ' yaml'

def yaml_save object, filename
  File.open filename, ' w' do |f|
    f.write(object.to_yaml)
  end
end

def yaml_load filename
  yaml_string = File.read filename
  YAML::load yaml_string
end

test_array = ['My name is Aslam!' ,
'I love coding in Ruby!' ,
'And in free time, I hangout with friends!' ]

filename = 'AboutMe.txt'
# We save it...
yaml_save test_array, filename
# We load it...
read_array = yaml_load filename

When we run this program from the command, it creates a text file in the same directory where the actual program file exists and writes the data given in the program.

No comments:

Post a Comment

Share your thoughts, Lets have a discussion :)