38
Ruby - String, Symbol and other scalar objects @farhan_faruque

Ruby - Strings, symbols, and other scalar objects

Embed Size (px)

Citation preview

Page 1: Ruby - Strings, symbols, and other scalar objects

Ruby - String, Symbol and other scalar objects

@farhan_faruque

Page 2: Ruby - Strings, symbols, and other scalar objects

What?

❖ Strings - handling text material of any length❖ Symbol - another way of representing text

Page 3: Ruby - Strings, symbols, and other scalar objects

String notation “This is a string” ‘This is also a string’

➔ single vs double-quoted string interpolation doesn’t work with single-quoted strings

puts "Two plus two is #{2 + 2}." => Two plus two is 4puts 'Two plus two is #{2 + 2}.' => Two plus two is #{2 + 2}.

Page 4: Ruby - Strings, symbols, and other scalar objects

Escape interpolation➔ Backslash(\) uses for escape the string interpolation mechanism in

a double-quoted string puts "Escaped interpolation: \"\#{2 + 2}\"."

=> Two plus two is #{2 + 2}.

Page 5: Ruby - Strings, symbols, and other scalar objects

QUOTING MECHANISMS

➔ % char {text}◆ %q produces a single-quoted string

puts %q{You needn't escape apostrophes when using %q.}

◆ %Q produces a double-quoted string

Page 6: Ruby - Strings, symbols, and other scalar objects

Basic String manipulation➔ retrieve the nth character in a string, use the [] operator/method

>> string = "Ruby is a cool language."=> "Ruby is a cool language.">> string[5]=> “i”>> string[-12]

=> “o”

➔ substring>> string[5,10]=> "is a cool "

Page 7: Ruby - Strings, symbols, and other scalar objects

Basic String manipulation..➔ Explicit substring search

>> string["cool lang"]=> "cool lang">> string["very cool lang"]=> nil

➔ slice!- remove the character(s) from the string permanently

>> string.slice!("cool ")=>"cool ">> string=>"Ruby is a language."

Page 8: Ruby - Strings, symbols, and other scalar objects

Basic String manipulation..➔ [] = method

- It takes the same kinds of indexing arguments as [] but changes the values to what you specify>> string["cool"] = "great"=> “great”>> string=> "Ruby is a great language."

Integers, ranges, strings, and regular expressions can thus all work as index or substring specifiers.

Page 9: Ruby - Strings, symbols, and other scalar objects

COMBINING STRINGS➔ use the + method

>> "a" + "b" + "c"

=> “abc”

➔ To add (append) a second string permanently, use the << method>> str = "Hi " => "Hi”>> str <<"there." => “Hi there”>> str => “Hi there”

Page 10: Ruby - Strings, symbols, and other scalar objects

COMBINATION VIA INTERPOLATION

>> str = "Hi " => "Hi " >> "#{str} there." => "Hi there."

➔ The code inside the curly braces can be anything.

Page 11: Ruby - Strings, symbols, and other scalar objects

Querying strings➔ BOOLEAN STRING QUERIES

include? - start_with? - end_with? - empty?>> string.include?("Ruby") => true>> string.start_with?("Ruby") => true

➔ CONTENT QUERIESsize length>> string.size=> 24

Page 12: Ruby - Strings, symbols, and other scalar objects

Querying stringscount method

- use for many times a given letter or set of letters occurs in a string>> string.count("a") => 3

- To count how many of a range of letters there are, you can use a hyphen-separated range>> string.count("g-m") => 5

- To negate the search,to count the number of characters that don’t match >> string.count("^aey. ") => 14

Page 13: Ruby - Strings, symbols, and other scalar objects

String comparison and ordering

➔ The String class mixes in the Comparable module and defines a <=> method>> "a" <=> "b" => -1the spaceship method/operator returns -1 if the right object is greater, 1 if the left object is greater, and 0 if the two objects are equal

➔ COMPARING TWO STRINGS FOR EQUALITY- string comparison method is ==

>> "string" == "string"=> true

Page 14: Ruby - Strings, symbols, and other scalar objects

String comparison and ordering➔ Another equality-test method, String#eql? same as ==

- String#equal? it tests whether two strings are the same object.>> "a".equal?("a")=> false

Page 15: Ruby - Strings, symbols, and other scalar objects

String transformation➔ CASE TRANSFORMATIONS >> string = "David A. Black" => "David A. Black" >> string.upcase => "DAVID A. BLACK" >> string.downcase => ”david a. black" >> string.swapcase => "dAVID a. bLACK" >> string.capitalize => "David A. Black"

Page 16: Ruby - Strings, symbols, and other scalar objects

String transformation➔ FORMATTING TRANSFORMATIONS

- The rjust and ljust methods expand the size of your string to the length provide in the first argument

>> string = "David A. Black" => "David A. Black"

>> string.rjust(25) => " David A. Black"

>> string.ljust(25) => "David A. Black "

>> string.rjust(25,'.') => "...........David A. Black"

Page 17: Ruby - Strings, symbols, and other scalar objects

String transformation➔ Stripping whitespace from either or both sides,using the strip ,

lstrip , and rstrip methods >> string = " David A. Black" => David A. Black " >> string.strip => "David A. Black" >> string.lstrip => "David A. Black " >> string.rstrip => " David A. Black"

Page 18: Ruby - Strings, symbols, and other scalar objects

String transformation➔ CONTENT TRANSFORMATIONS

- chop removes a character unconditionally- chomp removes a target substring if it finds that substring at the end of the

string>> "David A. Black".chop => "David A. Blac">> "David A. Black\n".chomp => "David A. Black">> "David A. Black".chomp(ck) => "David A. Bla"

- clear method, which empties a string of all its characters- replace , replaces the current content of the string

clear,replace method permanently changes the string.

Page 19: Ruby - Strings, symbols, and other scalar objects

String conversionsThe to_i method is one of the conversion methods available to strings.>> "100".to_i(17) => 289 #Interpret "100" as a base 17 number

Other conversion methods available to strings include - to_f (to float)-- to_s (to string;it returns its receiver) - to_sym or intern, which converts the string to a Symbol object. >> "1.2345and some words".to_f=> 1.2345

Page 20: Ruby - Strings, symbols, and other scalar objects

String encoding➔ SETTING THE ENCODING OF THE SOURCE FILE

- By default, Ruby source files use the US-ASCII encoding.- To change the encoding of a source file, we need to use a magic comment at

the top of the file. The magic comment takes the form# coding: encoding

Example:# coding: UTF-8puts "Euros are designated with this symbol: €"

=> Euros are designated with this symbol: €

Page 21: Ruby - Strings, symbols, and other scalar objects

String encoding➔ ENCODING OF INDIVIDUAL STRINGS

- we can encode a string with a different encoding, as long as the conversion from the original encoding to the new one—the transcoding—is permitted .

>> str.encode("UTF-8")=> "Test string

Page 22: Ruby - Strings, symbols, and other scalar objects

Symbols and their usesSymbols?

- instances of the built-in Ruby class Symbol- have a literal constructor: the leading colon

Example::a:book:”this is a symbol”

to_sym - create a symbol programmatically by calling the to_sym method

>> "a".to_sym=> :a

Page 23: Ruby - Strings, symbols, and other scalar objects

Characteristics of symbols➔ IMMUTABILITY

- Like an integer, a symbol can’t be changed.➔ UNIQUENESS

- Symbols are unique- symbols are more like integers than strings in this respect

>> "abc".object_id => 2707250>> "abc".object_id => 2704780>> :abc.object_id => 160488>> :abc.object_id => 160488

Ruby has no Symbol#new method

Page 24: Ruby - Strings, symbols, and other scalar objects

Symbols and identifiersSymbol.all_symbols

- returns list of all symbols- a table of symbol

Symbol added when - assign a value to a variable or constant- create a class- write a method

>> Symbol.all_symbols.size => 2025>> a = 1 =>1>> Symbol.all_symbols.size >> 2026>> Symbol.all_symbols.include?(:a) =>true

Page 25: Ruby - Strings, symbols, and other scalar objects

Symbols and identifiers➔ any symbol Ruby sees anywhere in the program is added>> a = :x => :x>> Symbol.all_symbols.size => 2027>> Symbol.all_symbols.include?(:x) =>true

Page 26: Ruby - Strings, symbols, and other scalar objects

Symbols in practice➔ SYMBOLS AS METHOD ARGUMENTS

attr_accessor :nameattr_reader :age

➔ SYMBOLS AS HASH KEYS>> d_hash = { :name => "David", :age => 49 } =>{:name=>"David", :age=>49}>>d_hash[:age] => 49

● symbols are more like integers then like strings● a variable to which a symbol is bound provides the actual symbol value, not

a reference to it

Page 27: Ruby - Strings, symbols, and other scalar objects

Numerical objects➔ numbers are objects

n = 99.6m = n.roundputs m

➔ Numerical classesNumeric

Float Integer

Fixnum Bignum

Page 28: Ruby - Strings, symbols, and other scalar objects

Times and datesrequire 'date', require 'time' package Times and dates are manipulated through three classes: Time , Date , and DateTime

● 'date' package the Date and DateTime classes● 'time' package enhances the Time class

Page 29: Ruby - Strings, symbols, and other scalar objects

Instantiating date/time objects➔ CREATING DATE OBJECTS

- Date.today constructor>> Date.today=> #<Date: 4909565/2,0,2299161>

- Date.new >> puts Date.new(1959,2,1)=> 1959-02-01

- parse constructor>> puts Date.parse("03/6/9")=> 2003-06-09

Page 30: Ruby - Strings, symbols, and other scalar objects

Instantiating date/time objects➔ CREATING TIME OBJECTSwe can create a time object using any of several constructors: new (a.k.a. now), at, local (a.k.a. mktime), and parse.>> Time.new=> 2008-12-03 12:16:21 +0000>> Time.at(100000000)=> 1973-03-03 09:46:40 +0000>> Time.mktime(2007,10,3,14,3,6)=> 2007-10-03 14:03:06 +0100

Page 31: Ruby - Strings, symbols, and other scalar objects

Instantiating date/time objects➔ CREATING DATETIME OBJECTS

>> puts DateTime.new(2009, 1, 2, 3, 4, 5)2009-01-02T03:04:05+00:00=> nil>> puts DateTime.now2008-12-04T09:09:28+00:00=> nil>> puts DateTime.parse("October 23, 1973, 10:34 AM")1973-10-23T10:34:00+00:00

Page 32: Ruby - Strings, symbols, and other scalar objects

Date/time query methodsTime objects can be queried as to their year, month, day, hour, minute, andsecond, as can datetime objects. Date objects can be queried as to their year, month, and day:>> dt = DateTime.now=> #<DateTime: 2008-12-04T09:11:32+00:00 26511892736584919/10800000000,0/1,2299161)>>> dt.year => 2008>> dt.hour => 9we can determine whether the given time/date is or isn’t a particular day of the week >> d.monday? => false

Page 33: Ruby - Strings, symbols, and other scalar objects

Date/time formatting methodsAll date/time objects have the strftime method, which allows to format their fields in a flexible way using format strings, in the style of the strftime(3) system library:>> t = Time.now=> 2008-12-04 09:22:09 +0000>>t.strftime("%m-%d-%Y")=> "12-04-2008"

Page 34: Ruby - Strings, symbols, and other scalar objects

Common time and date format specifiersSpecifier Description%Y Year (four digits)

%m Month (number)

%d Day of month (left-padded with zeros)

%a , %A Short day name, full day name

%H , %I Hour (24-hour clock), hour (12-hour clock)

%M Minute

%S Second

%x Equivalent to "%m/%d/%y"

Page 35: Ruby - Strings, symbols, and other scalar objects

Date/time conversion methodsTime has to_date and to_datetime methodsDate has to_time and to_datetime DateTime has to_time and to_date .DATE/TIME ARITHMETIC Time objects let you add and subtract seconds from them, returning a new time object>> t = Time.now=> 2008-12-04 09:33:43 +0000>> t - 20=> 2008-12-04 09:33:23 +0000

Page 36: Ruby - Strings, symbols, and other scalar objects

DATE/TIME ARITHMETICDate and datetime objects interpret + and – as day-wise operations, and they allow for month-wise conversions with << and >>>> dt = DateTime.now=> #<DateTime: 2015-03-25T22:00:10+06:00...>>> puts dt + 100=> 2015-07-03T22:00:10+06:00>> puts dt >> 3=> 2015-06-25T22:00:10+06:00>> puts dt << 10=> 2014-05-25T22:00:10+06:00

Page 37: Ruby - Strings, symbols, and other scalar objects

DATE/TIME ARITHMETICMove ahead one using the next (a.k.a. succ ) method.A whole family of next_unit and prev_unit methods move back and forth by day(s), month(s), or year(s):

>> d = Date.today => #<Date: 2008-12-04 (4909609/2,0,2299161)>>> puts d.next =>2008-12-05>> puts d.next_year => 2009-12-04>> puts d.next_month(3) =>2009-03-04>> puts d.prev_day(10) =>2008-11-24

Page 38: Ruby - Strings, symbols, and other scalar objects

Reference