RUBY vers. 2. The strings are written between or between (but in this case they will become interpreted) for ex.:



Similar documents
Chapter 2 Writing Simple Programs

Benvenuti a Coffee Break Italian - welcome to the lesson notes for the second episode

ING USING HOTMAIL

6.170 Tutorial 3 - Ruby Basics

Cifratura Dati in Tabelle MySQL

1 Stored Procedures in PL/SQL 2 PL/SQL. 2.1 Variables. 2.2 PL/SQL Program Blocks

Amy wants to use her to view some photos her friend Sandy sent, from her vacation to Washington DC.

Student Employment Website User Guide for Off-Campus Employers

Software Development (CS2500)

Eldy User's Manual. Contents

How-To: Write simple sieve scripts

Drupal Module Development

7.1 Our Current Model

PRI-(BASIC2) Preliminary Reference Information Mod date 3. Jun. 2015

G563 Quantitative Paleontology. SQL databases. An introduction. Department of Geological Sciences Indiana University. (c) 2012, P.

PostgreSQL Functions By Example

Project 2: Bejeweled

CS106A, Stanford Handout #38. Strings and Chars

Computers. An Introduction to Programming with Python. Programming Languages. Programs and Programming. CCHSG Visit June Dr.-Ing.

BBC LEARNING ENGLISH 6 Minute Grammar Future perfect continuous

Programming in Access VBA

Binary search algorithm

This chapter describes the specifications of the embedded Ethernet function for Series 16i/18i/21i/160i/180i/210i/160is/180is/210is B.

Special Notice. Rules. Weiss Schwarz Comprehensive Rules ver Last updated: October 15 th Outline of the Game

Python Loops and String Manipulation

Client Side Binding of Dynamic Drop Downs

FrontPage 2003: Forms

Ciphermail Gateway PDF Encryption Setup Guide

ESPResSo Summer School 2012

Normandale Community College Student Employment Website Employer User Guide Updated December 15, 2010

This activity will guide you to create formulas and use some of the built-in math functions in EXCEL.

Coding & Data Skills for Communicators Dr. Cindy Royal Texas State University - San Marcos School of Journalism and Mass Communication

Moving from CS 61A Scheme to CS 61B Java

Big Data & Scripting Part II Streaming Algorithms

Scanner. It takes input and splits it into a sequence of tokens. A token is a group of characters which form some unit.

Advanced BIAR Participant Guide

AUTHENTICATION... 2 Step 1:Set up your LDAP server... 2 Step 2: Set up your username... 4 WRITEBACK REPORT... 8 Step 1: Table structures...

GLBP - Gateway Load Balancing Protocol

Using Files as Input/Output in Java 5.0 Applications

Lab 4.4 Secret Messages: Indexing, Arrays, and Iteration

Exercise 1: Python Language Basics

Lecture 5: Java Fundamentals III

Contents 1. Introduction Login Order Status Search for pre-advice and orders View pre-advice or order...

ROM ACCESS CONTROL USER S MANUAL

Hosting Users Guide 2011

Using Format Manager For Creating Format Files

qwertyuiopasdfghjklzxcvbnmqwerty uiopasdfghjklzxcvbnmqwertyuiopasd fghjklzxcvbnmqwertyuiopasdfghjklzx cvbnmqwertyuiopasdfghjklzxcvbnmq

Chapter 11: Input/Output Organisation. Lesson 06: Programmed IO

Java from a C perspective. Plan

How To Use Standard Pos On A Pc Or Macbook Powerbook (Powerbook 2)

Creating Basic Excel Formulas

SQL Server Array Library László Dobos, Alexander S. Szalay

StreamServe Persuasion SP4 Service Broker

Yahoo Terminology

Send from your App Part 1

Hypercosm. Studio.

CAPIX Job Scheduler User Guide

Introduction to UNIX and SFTP

THE SET ANALYSIS. Summary

An Incomplete C++ Primer. University of Wyoming MA 5310

Exceptions in MIPS. know the exception mechanism in MIPS be able to write a simple exception handler for a MIPS machine

Creating an online survey using Sona Systems

Presidents Quiz. What You ll Learn

Section 1: Overture (Yahoo) PPC Conversion Tracking Activation

On your desktop double-click the Qqest Time and Attendance Systems icon:

First Java Programs. V. Paúl Pauca. CSC 111D Fall, Department of Computer Science Wake Forest University. Introduction to Computer Science

Python Lists and Loops

VoiSmart Fax Server. Administrator and User Manual Versione 1.0.0

Introduction to Data Structures

Android App Development Lloyd Hasson 2015 CONTENTS. Web-Based Method: Codenvy. Sponsored by. Android App. Development

Experiments: Labview and RS232

Using My NCBI and My Bibliography Tools to Complete the NIH Research Project Progress Report (RPPR)

Differences in Use between Calc and Excel

MS Access: Advanced Tables and Queries. Lesson Notes Author: Pamela Schmidt

User Manual Document HTTP-Direct / FTPServer and FLASH file system

SNAP Printer Web Server Users Manual

Importing Xerox LAN Fax Phonebook Data from Microsoft Outlook

Microsoft Excel 2010 Training. Use Excel tables to manage information

Bahamas Tax Information Exchange Portal Documentation

Web Development using PHP (WD_PHP) Duration 1.5 months

Advanced Programming with LEGO NXT MindStorms

Creating a Guest Book Using WebObjects Builder

Quick Start Guide: Mac vpad September 2007

ITALIAN AUDIO WORKBOOK.

Example of a Java program

User Guide and Tutorial Central Stores Online Ordering System. Central Stores Financial Services Western Washington University

ipratico POS Quick Start Guide v. 1.0

Getting Started with Excel Table of Contents

UTILITIES BACKUP. Figure 25-1 Backup & Reindex utilities on the Main Menu

Training Modules: Entering a New Transcript Part 2

Samsung Xchange for Mac User Guide. Winter 2013 v2.3

FTP protocol (File Transfer Protocol)

IRF2000 IWL3000 SRC1000 Application Note - Develop your own Apps with OSGi - getting started

INTER TRIBAL HEALTH AUTHORITY ELECTRONIC MEDICAL RECORD (EMR) CLERICAL TRAINING MANUAL

HowTo. Planning table online

Transcription:

Updated on December 15 2006 Thanks to Giulio Ardoino for his contribute. RUBY vers. 2 The strings are written between or between (but in this case they will become interpreted) for ex.: a = 2 (numbers must be written without apexes singles or doubles) puts 'a' ---> it will print a because between parenthesis the variable a is interpreted as string puts "a" ---> it will print a because between parenthesis the variable a is interpreted as string puts a ---> it will print 2 because the variable a is a number a = casa (the strings must be written with apexes otherwise we will have an error) puts 'a' ---> it will print a puts "a" ---> it will print a puts a ---> it will print casa A date is printed on video with instruction puts (the s means string) puts 4 + 4 --> it will print -- 8 puts 5**2 --> it will print -- 25 (5 at square) puts ' ' --> it will be empty puts 'You'are back' --> it will give error puts 'You\'re back' --> it will print -- You're back + joins the strings e/o numbers The variables The variables are not objects Declare a Variable: variabileuno = 'casa' variabiledue = 2 (numbers must be written without apexes, less then we don t want that 2 is a string) puts variabileuno *2 variabiletre = ' casa' puts variabiletre * 2 var1 = 20 var2 = var1 puts var1 --> it will print -- 20 puts var 2 --> it will print -- 20 var1 = 'seven' puts var1 --> it will print -- casacasa --> it will print -- casa casa --> it will print -- seven

puts var2 --> it will print -- 20 Methods The metho d s convert the dates of variables variable.converter.to_s --> it converts the variable in string.to_i --> it converts the variable in number var1 = 5 var2 = '12' puts var1.to_s + var2 --> it will print -- 512 (as string and not as number) var1 = 5 var2 = '12' puts var1 + var2.to_i --> it will print -- 17 (as number and not as string) Obtain dates from input of keyboard puts 'What\'s your name?' nome = gets (the function gets waits the inserting of dates from keyboard, but it leaves a space, i ) puts 'Ciao ' + nome + 'è bello conoscerti.' --> it will print --- Ciao Marco è --> bello conoscerti. nome = gets.chomp (writing chomp it s not considered the final space) Methods or functions If the objects (such as strings, entires and comma mobile) are names in Ruby, then the methods are like the verbs. Like every verb it needs of a name, every method needs of an object. Now many methods:.reverse (the variable is written on the contrary).length (writes in entire numbers and not in string the length of variable).to_s (it converts the variable in string).to_i (it convert the variable in entire).upcase (it writes the variable in upper case).downcase (it writes the variable small).swapcase ( ).capitalize (it writes the first letter in upper case).center (it insert the variable at center).ljust (it insert the variable on the left).rjust (it insert the variable on the right).times (repeat the variable more times -->see do).join (join ---> see the Array).slice (get the character for character of a string)

Random puts rand (give me random numbers with the comma) puts rand(1000) (give me entire numbers from 0 to 999) puts Control of flow > greater < minor == equal at!= different equal >= minor equal <= greater equal or && and IF ELSIF ELSE END ( it always goes inserted to the of every if and while) a = 10 b = 20 if a > b puts 'a is greater then b' elsif a == b puts 'a is equal at b' else puts 'a is minor than b' WHILE END ( it always goes inserted to the of every if e while) puts 'Indovina il numero' a = gets.chomp //the inserted number will be considered as string and not as number while a!= '100' puts 'Hai inserito il numero sbagliato' a = gets.chomp puts 'Hai indovinato il numero' Array and Iterators 0 1 2 3 citta = ['Lucca', 'Firenze', 'Pistoia', 'Siena'] puts citta ---> it will print -- tutte le città dall'alto verso il basso

puts ' ' ---> prints an empty row puts citta[0] ---> it will print -- Lucca puts citta[2] ---> it will print -- Pistoia puts citta[4] ---> it will print -- nil that is nothing because the array 4 doesn t exist each is a method used for array, it goes always used together to do and do it not a method. 0 1 2 3 citta = ['Lucca', 'Firenze', 'Pistoia', 'Siena'] citta.each do italia puts 'Io ho abitato in queste ' + italia + '.!' ---> it will print -- all the ---> towns toward down do, we see another use of do (do is not a method) 3.times do puts 'ciao' ---> it will print -- 3 times ciao from up toward down 0 1 2 3 citta = ['Lucca', 'Firenze', 'Pistoia', 'Siena'] 50.times do puts citta ---> it will print -- 50 times Lucca Firenze Pistoia Siena from up to down puts [ ] ---> it will print -- 50 times nothing, that is it won t do anything. Use methods to enliv the array.push (insert).pop (remove the last object from array).length (it says from how many elements in number is composed the array) citta=[ ] citta.push 'Lucca' ---> insert Lucca on array puts citta.length ---> the array is composed from 1 object citta.push 'Firenze' ---> insert Firenze in array citta.push 'Pistoia' ---> insert Pistoia in array puts citta.length ---> the array is composed from 3 objects citta.pop ---> delete Pistoia, that is the last object, from array puts citta.length ---> the array is composed from 2 objects We learn to write our methods or functions. A function starts with def and s with. If the objects in ruby are like the names in English, the methods are like the verbs. The methods have NOT to start with the letter upper case This below is an example of a method

def prova puts 'ciao' prova ---> it will print -- ciao The local variables live only inside the method, if you use them out of method, you will have an error. The local variables (inside the method) and outside from this, can have the same name, but they will never interfere one with the other. We use 1 local variable and 1 parameter (thanks to local variable called number): def prova numero puts 'ciao' * numero prova 3 ---> it will print -- ciao 3 times prova ---> will give an error because it misses a parameter (wrong number of arguments (0 for 1) (ArgumentError) We use 2 local variables number and double and we pass 3 parameters, redouble is always the name of method. def raddoppia numero doppio = numero*2 puts numero.to_s+' moltiplicato fa ' +doppio.to_s raddoppia 7 ---> it will print -- 6 moltiplicato fa 12 The last value returned, gives 1 method, it s the last expression valued and not the last string on method. Infact (sono una stringa) is between apexes, that means, that it is an expression. We use only 1 local variable and 1 expression at the of method. def raddoppia numero puts 'ciao'*numero 'sono una stringa' x = raddoppia 3 ---> it will print -- ciaocioacioa puts x ---> it will print -- sono una stringa Now we pass 3 dates to a method we have created, before we declare how many variables we use declaring the method (we can put them between parenthesis), after we recall the method passing to it the other variables, enough to consider the number (in this case are 3): def prova a, b, c

puts 'buon giorno ' + a + b c = 'Cristian ' d = 'Massimiliano ' e = Roberto prova c, d, e ---> it will print -- buon giorno Cristian Massimiliano Roberto Other example with method for ftp: require 'net/ftp' def f (ip, ut, pa) ftp = Net::FTP.new(ip) ftp.login(ut, pa) files = ftp.chdir('/directoryinventata/') ftp.putbinaryfile('/aggiornamento/file.tgz', 'file.tgz', 1024) ftp.putbinaryfile('/aggiornamento/file1.tgz', 'file1.tgz', 1024) ftp.putbinaryfile('/aggiornamento/file.sh', 'file.sh', 1024) ftp.close puts 'Inserisci l\' ip' ip = gets.chomp puts 'Inserisci utente' utente = gets.chomp puts 'Inserisci password' password = gets.chomp f ip, utente, password Classes and Objects A category of objects such as dogs is called class, and same specified object belonging to a class is called instance of the class. The class starts always withe the letter upper case. Dog is a class The object belonging to the class Cane is called instance. First we define the characteristics of the class, later we create an instance. class Dog def speak puts "Bau" The class Dog starts with class and s with speak is a method of the class lassie = Dog.new

lassie is the instance of the class Dog The method new create a new object, that is a new instance of the class. Now we decide to give to lassie a property (speak) lassie.speak Or we can exec temporarily the class like that: (Dog.new).speak or Dog.new.speak pochi is an instance of the class (it s a species of variable), instead Dog.new.speak will disappear just executed. Other example class Greeter def initialize name= "World" @name = name def say_hi puts "Hi #{@name}!" # "Hi " + @name + "!" def say_bye puts "Bye #{@name}, come back soon." # "Bye " + @name + ",come back soon." Greeter is the class @name is a variable of instance, available for all methods of a class We create an object: g = Greeter.new("Pat") #has been created the object g g.say_hi #we use the object using the methods g.say_bye #we use the object using the methods #g.@name #It s not possible use it class Greeter attr_accessor :name #How modify a class, doesn t change the objects that already exist, but it has effect on new objects that will be created. It has effect on variables of object. Greeter.new("Andy")

g.respond_to?("name") g.respond_to?("name=") g.say_hi #Stamperà Hi Pat! g.name="betty" g g.name g.say_hi #Stamperà Hi Betty! Example complete: class MegaGreeter attr_accessor :names # Create the object def initialize(names = "World") @names = names # Say hi to everybody def say_hi if @names.nil? puts "..." elsif @names.respond_to?("each") # @names is a list of some kind, iterate! @names.each do name puts "Hello #{name}!" else puts "Hello #{@names}!" # Say bye to everybody def say_bye if @names.nil? puts "..." elsif @names.respond_to?("join") # Join the list elements with commas puts "Goodbye #{@names.join(", ")}. Come back soon!" else puts "Goodbye #{@names}. Come back soon!" if FILE == $0

mg = MegaGreeter.new #I create the object mg from class MegaGreeter mg.say_hi #It prints Hello World! mg.say_bye #Goodbye World. Like back soon! # Change name to be "Zeke" mg.names = "Zeke" #I change the value to variable of the object mg.say_hi mg.say_bye #It prints Hello Zeke! #It prints Hello Zeke. Like back soon! # Change the name to an array of names mg.names = ["Albert", "Bra", "Charles", "Dave", "Englebert"] mg.say_hi #It prints Hello Albert! #It prints Hello Bra! #It prints Hello Charles! #It prints Hello Dave! #It prints Hello Englebert! mg.say_bye #stampa Goodbye Albert, Bra, Charles, Dave, Englebert. Come back soon! # Change to nil mg.names = nil #I change name at variable leaving empty mg.say_hi #It prints... mg.say_bye #It prints... Stamperà a video: Hello World! Goodbye World. Come back soon! Hello Zeke! Goodbye Zeke. Come back soon! Hello Albert! Hello Bra! Hello Charles! Hello Dave! Hello Englebert! Goodbye Albert, Bra, Charles, Dave, Englebert. Come back soon!...... Write and read a file Write in a file: file = prova.txt testo = 'Prova di scrittura in un file' ---> I insert the text File.open file, 'w' do f ---> I use the method File.open I read the ---> I insert the name of file in a variable

- - - > file, with the cycle do I read byte for byte f.write testo ----> I write the string of variable testo - - - > I close the cycle do Read a file (2 ways): 1) file = 'prova.txt' --->I insert the name of file in a variable lettura = File.read file ---> I use the method File.read to read the variable file puts lettura - - > Using puts I read the variable lettura or 2) IO.foreach("prova.txt") { line puts line } - - - > For each line read from prova.txt, - - - > it prints on video 1 line Read a row of 1 file and get the characters: arr = IO.readlines("rimmer.txt") ---> I read of file rimmer.txt a = arr[6] ---> I insert the row 5 of array into variable a puts a.slice(9..14) ---> I print the letters from 9 to 14 of the row 5 of array Write and read of file using the method yaml and using an array require 'yaml' - - - > I use the method yaml array = ['ciao', 'io', 'sono', 'Luca'] - - - > I insert the dates in a array test = array.to_yaml - - - > Using the method yaml, I insert the array - - - > into variable testo puts test - - - > We print on video the variable test file = 'rimmer.txt' File.open file, 'w' do f f.write test into file lettura = File.read file made of file rimmer.txt leggiarray = YAML::load lettura puts leggiarray - - - > We create the file rimmer.txt - - - > I use the method File.open in writing - - - > to write into variable file with do - - - > I write the variable text (the array) - - - > I finish the cycle - - - > Into variable lettura I insert the read - - - > Using YAML::load I read the file - - - > lettura that I insert in a variable - - - > I read leggiarray