Please note: This page is imported from my wiki, which hasn't been updated in over 10 years. Some of the formatting was lost during the import. I'll try to get around to fixing it someday.
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
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”] |
arrayname = [“first”, “second”, “third”] arrayname = %w(“one two three four five”) array_name[4] = “forth”
arrayname.length arrayname.reverse arrayname.sort arrayname.include? element
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
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(directoryname) unless File.directory?(directoryname)
filehandle = File.open(“filename”, “a”) filehandle.puts “some string” filehandle.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
Andrew McDonough is a consultant CTO and software developer, currently based between Berlin and London.
Follow Andrew on Twitter or Connect on LinkedIn