Ruby is an object oriented scripting language. Ruby is of particular interest because of the popular framework Ruby on Rails
irb --simple-prompt
ri ClassName ri ClassName#method_name
Use the ARGV array:
ARGV[0]
invar = gets # Getting rid of the newline invar.chomp
Blocks of code can either be defined using curly brackets {}, or on multiple lines using the end keyword to terminate the block e.g.
def something ... end
continue them with a backslash \
if myvar == "something" .. elsif myvar == "somethingelse" .. else .. end
10.times do puts "hello" end
while condition .. end
== !- < > ⇐ >=
Inside a quoted string, use curly braces and a hash e.g.
"This is a string with some #{variable} in it.
Use a template with a %s symbol, then you can reuse it later:
template = "This is a template where %s will be substituted" puts template % "subsituted string"
Or with multiple substitutions:
template = "There are multiple strings here like %s and %s" puts template % ["one","two"]
| Operation | Syntax | Result |
|---|---|---|
| Assignment | s = “Andrew McDonough | “Andrew McDonough” |
| Length | s.length | “16” |
| Reversing | s.reverse | “hguonoDcM werdnA” |
| Substring | s.slice(2,4) | “drew” |
| Substitution | s.gsub(/n/,'z') | “Azdrew McDozough” |
| Split into Array | s.split(” ”) | [“Andrew”, “McDonough”] |
array_name = ["first", "second", "third"]
array_name = %w("one two three four five")
array_name[4] = "forth"
array_name.length array_name.reverse array_name.sort array_name.include? element+ - * operators for joining, difference and repeating
multi_array = [[1,"one"],[2,"two"]]
array_name.each do |element| ... end
hash_name = {
"key1" => "value1",
"key2" => "value2",
"key3" => "value3",
}
hash_name.each do |key, value| ... end
def some_function { puts “print it!” }
Similarly to other scripting languages, the eval command causes the interpreter to execute a string:
eval "puts 'Hello World!'"
def some_function
yield # where the code block is substituted
end
You can convert a block to an object. This preserves the current execution environment. The object is known as a proc. One way of doing this is using the lambda function.
p = lambda { |somevar| puts "somevar" + somevar }
p.call
Defining Classes:
class <ClassName>
def initialize(somevar)
@attrib = attrib
end
end
c_instance = ClassName.new
The null object in Ruby is called nil
Dir.open("some/path/").each do |dir|
next if ["..","."].include? dir # Skip . and ..
puts dir # Or some other operation
end
FileTest.exist?(file_name)
Dir.mkdir(directory_name) unless File.directory?(directory_name)
file_handle = File.open("file_name", "a")
file_handle.puts "some string"
file_handle.close
TK, the graphics toolkit that is normally used in TCL can also be called from Ruby
require 'tk' app = TkRoot.new TkLabel.new(app) do text "Hellow World!" end Tk.mainloop