Basic ruby syntax
Download
1 / 23

Basic Ruby Syntax - PowerPoint PPT Presentation


  • 83 Views
  • Uploaded on

Basic Ruby Syntax. No variable declarations. sum = 0 i = 1 while i <= 10 do sum += i * i i = i + 1 end puts "Sum of squares is #{sum}\n". Newline is statement separator. do ... end instead of { ... }. Optional parentheses in method invocation. Substitution in string value.

loader
I am the owner, or an agent authorized to act on behalf of the owner, of the copyrighted work described.
capcha
Download Presentation

PowerPoint Slideshow about 'Basic Ruby Syntax' - saxon


An Image/Link below is provided (as is) to download presentation

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.


- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript
Basic ruby syntax
Basic Ruby Syntax

No variable declarations

sum = 0

i = 1

whilei <= 10 do

sum += i*i

i = i + 1

end

puts "Sum of squares is #{sum}\n"

Newline is statement separator

do ... end instead of { ... }

Optional parentheses

in method invocation

Substitution instring value

CS 142 Lecture Notes: Ruby


Variable names and scopes
Variable Names and Scopes

foo Local variable

$foo Global variable

@foo Instance variable in object

@@foo Class variable

MAX_USERS “Constant” (by convention)

CS 142 Lecture Notes: Ruby


Ruby string syntax
Ruby String Syntax

  • Single quotes (only \' and \\)

    'Bill\'s "personal" book'

  • Double quotes (many escape sequences)

    "Found #{count} errors\nAborting job\n"

  • %q (similar to single quotes)

    %q<Nesting works: <b>Hello</b>>

  • %Q (similar to double quotes)

    %Q|She said "#{greeting}"\n|

  • “Here documents”

    <<END

    First line

    Second line

    END

CS 142 Lecture Notes: Ruby


Arrays and hashes
Arrays and Hashes

x = Array.new

x << 10

x[0] = 99

y = ["Alice", 23, 7.3]

x[1] = y[1] + y[-1]

person = Hash.new

person["last_name"] = "Rodriguez"

person[:first_name] = "Alice"

order = {"item" => "Corn Flakes", "weight" => 18}

order = {:item => "Corn Flakes", :weight => 18}

order = {item: "Corn Flakes", weight: 18}

CS 142 Lecture Notes: Ruby


Ruby statements
Ruby Statements

if x < 10 then

...

elsifx < 20

...

else

...

end

while x < 10 do

...

end

array = [14, 22, 34, 46, 92]

for value in array do

...

end

CS 142 Lecture Notes: Ruby


Factorial
Factorial

deffac(x)

if x <= 1 then

return 1

end

return x*fac(x-1)

end

CS 142 Lecture Notes: Ruby


Arguments defaults variable
Arguments: Defaults, Variable #

definc(value, amount=1)

value+amount

end

defmax(first, *rest)

result= first

for x in rest do

if (x > result) then

result= x

end

end

returnresult

end

CS 142 Lecture Notes: Ruby


Keyword arguments
Keyword Arguments

defcreate_widget(size, properties)

...

end

create_widget(6, {:id => "table22", :class => "Cart"})

create_widget(6, :id => "table22", :class => "Cart")

create_widget(6, id: "table22", class: "Cart")

CS 142 Lecture Notes: Ruby


Default hash keyword
Default, Hash, Keyword

def f_default(size=10, color="black", bg="white")

def f_hash(properties)

def f_keyword(size:10, color:"black", bg:"white")

f_default 20 #+

f_default 20, "green", "red" #+

f_default 20, bg="red" #?

f_hash 20 #-

f_hash({:size => 20}) #+

f_hash(:bg => "red", :color => "green", :size => 20)#+

f_hash(bg:"red", color:"green", size:20) #+

f_keyword(bg:"red", color:"green", size:20) #+

f_keyword 20, "red" #-

CS 142 Lecture Notes: Ruby


Calling functions
Calling Functions

def max(first, *rest)

end

max(5,6)

max 5,6

max (5,6) # Avoid!

CS 142 Lecture Notes: Ruby


Symbols vs strings
Symbols vs. Strings

staff = ["Phil", "Firas", "JJ", "Andy"]

faculty = ["Phil"]

staff = [:Phil, :Firas, :JJ, :Andy]

faculty = [:Phil]

faculty

"Phil"

"Phil"

with Strings

"Firas"

staff

"JJ"

"Andy"

faculty

:Phil

with Symbols

:Firas

staff

:JJ

:Andy

CS 142 Lecture Notes: Ruby


Equivalent code
Equivalent Code

array = [14, 22, 34, 46, 92]

for value in array do

print(value, "\n")

end

array = [14, 22, 34, 46, 92];

array.eachdo |value|

print(value, "\n")

end

Block: code passedto method

CS 142 Lecture Notes: Ruby


Blocks iterators yield
Blocks, Iterators, Yield

odd_numbers(3) do |i|

print(i, "\n")

end

defodd_numbers(count)

number = 1

while count > 0 do

yield(number)

number += 2

count -= 1

end

end

Block: code passedto method

Invoke method’s block

CS 142 Lecture Notes: Ruby


Blocks map select reduce
Blocks: Map, Select, Reduce

names = ['Vien', 'Omosola', 'Sarah']

lookup = {'Vien' => 'viendinh',

'Omosola' => 'omosolao',

'Sarah' => 'ssterman'}

logins = names.mapdo |n|

lookup[n]

end

vnames = names.selectdo |n|

n[0] == 'V'

end

namelist = names.reducedo |sum,val|

sum = sum + " and " + val

end

CS 142 Lecture Notes: Ruby


Iterators are reusable
Iterators are Reusable

defsum_odd(count)

sum = 0

odd_numbers(count) do |i|

sum += i

end

return sum

end

defodd_numbers(count)

number = 1

while count > 0 do

yield(number)

number += 2

count -= 1

end

end

CS 142 Lecture Notes: Ruby


Simple class
Simple Class

class Point

definitialize(x, y)

@x = x

@y = y

end

defx

@x

end

defx=(value)

@x = value

end

end

p = Point.new(3,4)

puts "p.x is #{p.x}"

p.x = 44

CS 142 Lecture Notes: Ruby


Reduce example extending array
Reduce Example (extending Array)

namelist = names.ereducedo |sum,val|

sum = sum + " and " + val

end

class Array

def ereduce()

sum = self[0]

if (size < 2) then

return sum

end

values =last(size - 1)

values.eachdo |v|

sum = yield(sum, v)

end

return sum

end

end

CS 142 Lecture Notes: Ruby


Module examples
Module Examples

module FileSaver

def FileSaver::try_saving_file(input, dir, name)

end

end

require 'file_saver.rb'

FileSaver::try_saving_file "Test", "./", "test.txt"

module ConfigurationParams

ROOT_DIR = "/home/pal"

USER_NAME = "pal"

end

CS 142 Lecture Notes: Ruby


E reduce mixin
ereduceMixin

module EReduce

def ereduce()

sum = self[0]

if (size < 2) then

return sum

end

values =last(size - 1)

values.eachdo |v|

sum = yield(sum, v)

end

return sum

end

end

class Array

include EReduce

end

CS 142 Lecture Notes: Ruby


Mixin example
Mixin Example

New methods available in MyClass:

min, max, sort, map, select, ...

classMyClass

include Enumerable

...

defeach

...

end

def<=>

...

end

end

CS 142 Lecture Notes: Ruby


Simple class1
Simple Class

class Point

definitialize(x, y)

@x = x

@y = y

end

defx

@x

end

defx=(value)

@x = value

end

end

p = Point.new(3,4)

puts "p.x is #{p.x}"

p.x = 44

CS 142 Lecture Notes: Ruby


Metaprogramming
Metaprogramming

  • Programs that write programs!

  • eval, instance_eval, class_eval

class Automobile

include Extendable

End

a = Automobile.new

a.add_variable :color

a.add_variable :brand

a.color = "green"

a.brand = "Mazda"

puts a.color, a.brand

Mixin that gives the

add_variablemethod

These method invocations

add accessor functions

CS 142 Lecture Notes: Ruby