RUBY - Motorola Solutions LaunchPad Developer Community
RUBY - Motorola Solutions LaunchPad Developer Community
RUBY - Motorola Solutions LaunchPad Developer Community
- No tags were found...
You also want an ePaper? Increase the reach of your titles
YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.
<strong>RUBY</strong> – Getting StartedGareth Lewis
Welcome• Gareth Lewis• <strong>Motorola</strong> <strong>Solutions</strong>
RubyLanguage• Dynamic• Object-Oriented• FriendlyRuby on Rails• Web Framework• Made Ruby popularRhodes• Inspired by RoR
CORE <strong>RUBY</strong>Ruby 1.9.3
Data TypesNumbersInteger types:FixnumBignumWhat‟s the difference?
Example 1num = 100014.times doputs “#{num.class}: #{num}”num *= numend
Operations• + Addition• - Subtraction• * Multipliation• / Division – Based upon type• % Modulus• ** Exponent
Data TypesFloatRationalComplex
StringsStrings in Ruby• Strings are simply sequences of characters*• Can use single or double quotes• Double quotes use more processing• Four ways to create strings• “Hello world”, „Hello world‟• %q!hello world! – single quote• %Q!hello world! – double quote• Here documents
string =
String interpolationrequire „time‟name = “Gareth”puts “Hello “ + name + “ it is now “ + Time.nowOrputs “Hello #{name} it is now #{Time.now}”
String encodingsrequire „time‟name = “Gareth”puts “Hello “ + name + “ it is now “ + Time.nowOrputs “Hello #{name} it is now #{Time.now}”
Methods
methodsMethods in Ruby similar to methods in otherlanguages.All methods must belong to a class similar to Java, butyou don‟t have to define the class. Confused?
Example 2Definition and calldef double(p1)endp1*2double(2) => 4double(“Hello”) => “HelloHello”Object.methods()Object.methods(false)
Variables
variablesDefining a variable• a = “Hello World”• Don‟t need to specify the type used, inferred fromcontent• Can redefine at any time in the program• a = 15• Type has now changed as well as content
Strong Dynamic Typing• Strong: all variables always have an explicit type• Dynamic: type for variable can change at any time.person = “Gareth”puts “The object in „person‟ is a #{person.class}”puts “The object has an id of #{person.object_id}”puts “and a value of „#{person}‟”
ProducesThe object in 'person' is a StringThe object has an id of 22693044and a value of Gareth
Aliasingperson1 = “Tim”person2 = person1person1[0] = „J‟puts “person1 is #{person1}”puts “person2 is #{person2}”person1 is Jimperson2 is Jim
How do we fix this?person1 = “Tim”person2 = person1.dupperson1[0] = „J‟puts “person1 is #{person1}”puts “person2 is #{person2}”person1 is Jimperson2 is Tim
Collections
ArrayEasy to create• a = [1,2,3,4,‟a‟,‟b‟,‟c‟]• a = Array.new(1,2,3,5,‟a‟,‟b‟,‟c‟) # Not commonlyused.Easy to access and modifya[2] #=> 3a[0] = 1000a[100] # ? => nil, not a run time error.a[-1] # ? => “c”
Dynamically sized.a = [1, 2]a[2] = 3a # => [1, 2, 3]a = [1, 2]a[3] = 3a # => [1, 2, nil, 3]
HashKey-Value Store• AKA: HashTable, Dictionary, Associative Array• Key is unique
HashKey-Value Store• AKA: HashTable, Dictionary, Associative Array• Key is uniqueEasy to create• h = {“name” => “Gareth”, “language” => “Ruby”}
HashKey-Value Store• AKA: HashTable, Dictionary, Associative Array• Key is uniqueEasy to create• h = {“name” => “Gareth”, “language” => “Ruby”}Easy to access• Array like syntax• h[“name”] => “Gareth”• h[“age”] => nil• h[“age”] = 38• {"name"=>"Gareth", "language"=>"Ruby", "age"=>38}
HashInsertion order. Prior to Ruby 1.9 all Hashes had an unordered listof keys.SymbolsBegin with a : (colon)Follow the same convention as a variable:name:age, etca = {:name => “Gareth”, :age => 38}
HashInsertion order. Prior to Ruby 1.9 all Hashes had an unordered listof keys.SymbolsBegin with a : (colon)Follow the same convention as a variable:name:age, etca = {:name => “Gareth”, :age => 38}]Why?Space. Symbols are a constant size and are immutable. If you useStrings to represent keys, Ruby has to store the string, and itmay store multiple copies.
RangeUseful with dates.require „Date‟jan1 = Date.new(2012, 1, 1)dec31 = Date.new(2012, 12, 31)dates = (jan1..dec31)dates.include?(Date.today) # => truedates.include?(Date.today + 365) # => false
Regular Expressions
Regular ExpressionsTools for testing Regular Expressions in Ruby• irb• Rubular
Conditionals and Loops
If statementsif• if input == “quit”exitendIf the statement doesn‟t have an else can be rewritten• exit if input == “quit”unless• unless input == “quit”do_workend• do_work unless input == “quit”
elseTest multiple conditions• if input == “quit”exitelsif input == “pause”sleep 20elsedo_workend• Note spelling of elsif• Unless can also be used with else, but it is confusing, so use if,if you want to use else.
CaseVery powerful case statement• case inputwhen "quit"exitwhen "pause"sleep 20when /\d\d\d\d-\d\d-\d\d/puts "The input looks like a date"when Stringputs "The input is #{input}"when 5..10puts "The input was between 5 and 10"elseputs "I don't understand you."end
whileSimple while loop• countwhile count < 10puts countcount += 1endcount += 1, cannot use ++, does not exist in RubyInline while• count = 0• puts count += 1 while count < 10
untiluntil is the inverse of while• count = 0until count >= 10puts countcount += 1endInline until• count = 0puts count += 1 until count >= 10
forFor exists in Ruby, but is very limited• for i in 1..5puts “Value of local variable is #{i}”end
forFor exists in Ruby, but is very limited• for i in 1..5puts “Value of local variable is #{i}”end• No equivalent of• for (int i = 0; i < 10; i += 2) using Ruby for loop
forFor exists in Ruby, but is very limited• for i in 1..5puts “Value of local variable is #{i}”end• No equivalent of• for (int i = 0; i < 10; i += 2) using Ruby for loop• We don‟t use it in Ruby
IterationThe Ruby Way
eachUse each for iterating• a = [1,2,3,4]a.each do |number|puts “The number is #{number}”end
eachUse each for iterating• a = [1,2,3,4]a.each do |number|puts “The number is #{number}”endUse do & end for multi-line, use {} for single line• a.each { |i| puts “The number is #{i}” }
eachUse each for iterating• a = [1,2,3,4]a.each do |number|puts “The number is #{number}”endUse do & end for multi-line, use {} for single line• a.each { |i| puts “The number is #{i}” }Same syntax works for other forms of iterating• .map• .each_with_index• .each_key• .select• .reject
Objects
ObjectsObjects• class PersonendInheritance• class Programmer < PersonendConstructors• class Persondef initialize(name)@name = nameenddef to_s“Name: #{@name}”endendp = Person.new(“Gareth”)
ObjectsAttributesHow do we access attributes?
ObjectsAttributesHow do we access attributes?Attribute readers and writers• class Personattr_reader :namedef initialize(name)@name = nameendendp = Person.new(“Gareth”)puts p.name
ObjectsAttributesHow do we set these?
ObjectsAttributesHow do we set these?• class Persondef initialize(name)@name = nameenddef name=(new_name)@name = nameendendp = Person.new(“Gareth”)p.name = “James”puts p.name
ObjectsAttributesHow do we set these? Simpler way• class Personattr_accessor :namedef initialize(name)@name = nameendendp = Person.new(“Gareth”)p.name = “James”puts p.nameOr attr_writer, though this is rare
IRBInteractive Ruby
TITLE HERE54.543.532.521.510.50Category 1 Category 2 Category 3 Category 4Series 1Series 2Series 3