110 likes | 274 Views
Ruby Data Types. and other languages… . Ruby Data Types: Array. Compare to Java/C++. Array literals/initialization a = [1,2,3] a2 = [-10..0, 0..10] a3 = [[1,2],[3,4]] a4 = [w*h, w, h] a5 = [] empty = Array.new zeros = Array.new(5, 0) Arrays are heterogeneous
E N D
Ruby Data Types and other languages…
Ruby Data Types: Array Compare to Java/C++ • Array literals/initialization a = [1,2,3] a2 = [-10..0, 0..10] a3 = [[1,2],[3,4]] a4 = [w*h, w, h] a5 = [] empty = Array.new zeros = Array.new(5, 0) • Arrays are heterogeneous • length and size return # of elements • Access beyond end of array returns nil • Elements can be accessed similar to strings • Arrays can be dynamically resized (can assign past the end of the array) • Use | and & for union and intersection
More arrays • words = %w[here we go again] => [‘here’,’we’,’go’,’again’] • Use << to append • Use * to replicate (e.g., a[0] * 3) • Useful functionality alphabet = ('A'..'Z').to_a alphabet.each {|c| print c } • Not covered: lots of methods, like clear, empty?, compact!, sort, sort!, pop, push, reverse, etc.
Symbol Get used to symbols, they’re used a lot Immutable, interned string (only one copy) Colon-prefixed, e.g., :one Commonly used as hash key Also stores names of classes, methods and variables in symbol table – more efficient than storing as string, can be used with reflection If your code is using a string as a unique identifier, consider using a symbol instead Methods available to convert between string and symbol
Hashes Required sometimes, e.g., Python Hashes supported directly in Perl, Python (dictionary) and Ruby and in class libraries of Java, C++ and C# Aka maps, associative arrays colors = { :Cyndi => "orange", :Karyl => "purple" } colors2 = { "Cyndi" => "orange", "Karyl" => "purple" } colors3 = { Cyndi: "orange", Karyl: "purple" } puts colors3[:Cyndi] colors.each do |key, value| puts "#{key}'s favorite color is #{value}" end Best to use immutable objects as keys Not covered: hash codes
Array vs Hash Which is better if need to access items in order? Which is useful for direct access? Hash: useful for “paired” data
Range parentheses required, else just applies to 3 Subrange introduced in Pascal, also used in Modula-2 and Ada. Others? • Purpose • determine if a value is in or out of range • iteration • Can be any value that implements <=> function (like CompareTo… why is this needed?) • 1..10 includes 10 • 1…10 excludes 10 coldwar = 1945..1989 coldwar.include? birthdate.year (1..3).to_a
Booleans Compare to Java/C++/C TrueClass singleton, write as true FalseClass singleton, write as false nil means no value. Test directly (o == nil) or with nil? true != 1, false != 0
Topic Summary • Language Concepts • Array • Heterogeneous? • Array operations • Fixed or dynamic size • Hash • key restrictions • Range • operations • Boolean • 0/1? • Ruby • Arrays • new • each • Symbols • Hashes • Range • Boolean