SCRIPTING IN RUBY By Amber Bennett “Ruby is simple in appearance, but is very complex inside, just like our human body.” --Yukihiro Matsumoto
HISTORY Created by Yukihiro Matsumoto Initial release in 1995 Matsumoto desired a scripting language with object-oriented support Photo Credit: "Yukihiro Matsumoto EuRuKo 2011" by Mathias Meyer - Licensed under Creative Commons Attribution-Share Alike 2.0 via Wikimedia Commons -
NAMES, BINDINGS, AND SCOPES Variable names can start with numbers, letters, and any combination of the two They must start with a letter or an underscore Variable names are descriptive Case sensitivity: Class names must be capitalized Variable names are begun with lowercase letters
Class variables Exist in the scope of a class Instance variables Unique to a given instance of a class Constants Do not change throughout execution of a program Can be reassigned, but interpreter will give a warning
DATA TYPES Dynamically typed Class variables start with Instance variables start Constants begin with a capital letter String type Number type Symbols Arrays and Hashes Abstract Data Types Provided through classes in Ruby
STRINGS: THE DIFFERENCE BETWEEN SINGLE AND DOUBLE QUOTES Double QuotesSingle Quotes The code sample: “The time is #{Time.now}” Prints out: The time is :26: The code sample: ‘The time is #{Time.now}; Prints out: The time is \#{Time.now}
SYMBOLS 1. # p039xysymbol.rb 2. know_ruby = :yes 3. if know_ruby == :yes 4. puts 'You are a Rubyist' 5. else 6. puts 'Start learning Ruby' 7. end Source:
ARRAYS AND HASHES Common among other languages 0 indexed Arrays are defined by [] Hashes are defined by curly braces in the format: hash_name = { :key1 => “value1”, :key2 => “value2” }
EXPRESSIONS AND ASSIGNMENT STATEMENTS Operators [] []=Assignment * / % + **Arithmetic Comparison .. …Range & ^ |AND, XOR, regular OR (bitwise) || && not or andLogical operators Ternary operator: expression ? value_if_true : value_if_false
STATEMENT-LEVEL CONTROL STRUCTURES If-statements Then, else, end Case Expressions Blocks 1. if sum == 0 then 2. if count == 0 then 3. result = 0 4. end 5. else 6. result = 1 7. end
CASE EXPRESSIONS
OBJECT-ORIENTED SUPPORT Matsumoto created Ruby with object-oriented support in mind A lot of functionality when dealing with files Matsumoto “wanted a scripting language that was more powerful than Perl, and more object-oriented than Python.” Video!
CONCURRENCY AND EXCEPTION AND EVENT HANDLING Logical concurrency Global Interpreter Lock (GIL) Exceptions can be caught using “rescue”
SOURCES Code samples taken from (unless otherwise specified):