Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Structure of Ruby Programs

Tags:

ruby

I need some insight into the construction of Ruby programs. I'm trying to learn how to write Ruby (independent of Rails) so I'm translating some Perl scripts I wrote in a bioinformtatics project into Ruby code. Basically creating classes where useful and whatnot.

My issue is how do I execute it? The Perl scripts are just long blocks of commands, one after the other. What's appropriate in Ruby? Should I define my classes in their own .rb files and call those and their methods in a sepearate rb file that sort of uses them to execute my program?

What is normally done? Any examples would be greatly apreciated. I'd also appreciate any tips in general on how to go about learning this kind of thing.

like image 656
Chris Hawkins Avatar asked Apr 28 '12 22:04

Chris Hawkins


People also ask

How many types are there to structure and execute the Ruby program What are they?

There are five types of variables supported by Ruby.

How does Ruby program work?

During the parsing stage, Ruby transforms the text into something called an abstract syntax tree, or AST. The abstract syntax tree is a representation of your program in memory. You might say that programming languages in general are just more user-friendly ways of describing abstract syntax trees.

What is Ruby programming?

Ruby is a general purpose programming language typically used for web development. Ruby makes it easy to store data after the user has navigated away from the page or closed the browser, and create, update, store, and retrieve that data in a database.


2 Answers

Ruby does have what's usually called the top level execution environment, and so a long string of commands will execute immediately just like Perl. Or, you can define classes and modules and go all OOP on your problem if you want, or you can mix the approaches.

You will need at least one line at the top level or top level of a class to start everything off. So:

p :hello

or

class A
  p :hello
end

or

class A
  def run
    p :hello
  end
end
A.new.run

or, my favorite:

class A
  def run
    p :hello
  end
  self
end.new.run
like image 69
DigitalRoss Avatar answered Oct 10 '22 09:10

DigitalRoss


I'd highly recommend looking at some of your other favorite gems to see how their code is structured (like on Github). That's how I found my start. Thinking of your project as a "gem", being released or not, is a good way to wrap your mind around the problem.

like image 26
Ben Kreeger Avatar answered Oct 10 '22 09:10

Ben Kreeger