Ruby Programming

Total Page:16

File Type:pdf, Size:1020Kb

Ruby Programming Ruby Programming Wikibooks.org December 1, 2012 On the 28th of April 2012 the contents of the English as well as German Wikibooks and Wikipedia projects were licensed under Creative Commons Attribution-ShareAlike 3.0 Unported license. An URI to this license is given in the list of figures on page 249. If this document is a derived work from the contents of one of these projects and the content was still licensed by the project under this license at the time of derivation this document has to be licensed under the same, a similar or a compatible license, as stated in section 4b of the license. The list of contributors is included in chapter Contributors on page 243. The licenses GPL, LGPL and GFDL are included in chapter Licenses on page 253, since this book and/or parts of it may or may not be licensed under one or more of these licenses, and thus require inclusion of these licenses. The licenses of the figures are given in the list of figures on page 249. This PDF was generated by the LATEX typesetting software. The LATEX source code is included as an attachment (source.7z.txt) in this PDF file. To extract the source from the PDF file, we recommend the use of http://www.pdflabs.com/tools/pdftk-the-pdf-toolkit/ utility or clicking the paper clip attachment symbol on the lower left of your PDF Viewer, selecting Save Attachment. After extracting it from the PDF file you have to rename it to source.7z. To uncompress the resulting archive we recommend the use of http://www.7-zip.org/. The LATEX source itself was generated by a program written by Dirk HÃijnniger, which is freely available under an open source license from http://de.wikibooks.org/wiki/Benutzer:Dirk_Huenniger/wb2pdf. This distribution also contains a configured version of the pdflatex compiler with all necessary packages and fonts needed to compile the LATEX source included in this PDF file. Contents 1 Overview . 3 1.1 Features . 3 1.2 References . 6 2 Installing Ruby . 7 2.1 Operating systems . 7 2.2 Building from Source . 10 2.3 Compile options . 10 2.4 Testing Installation . 10 2.5 References . 11 3 Ruby editors . 13 4 Notation conventions . 15 4.1 Command-line examples . 15 5 Interactive Ruby . 17 5.1 Running irb . 17 5.2 Understanding irb output . 18 6 Mailing List FAQ . 19 7 Basic Ruby - Hello world . 21 7.1 Hello world . 21 7.2 Comments . 22 7.3 Executable Ruby scripts . 22 8 Basic Ruby - Strings . 27 8.1 String literals . 27 8.2 Single quotes . 27 8.3 Double quotes . 28 8.4 puts . 29 8.5 print . 29 8.6 See also . 30 9 Basic Ruby - Alternate quotes . 31 9.1 Alternate single quotes . 31 9.2 Alternate double quotes . 32 10 Basic Ruby - Here documents . 33 10.1 Here documents . 33 10.2 Indenting . 34 10.3 Quoting rules . 35 11 Basic Ruby - Introduction to objects . 37 11.1 What is an object? . 37 11.2 Variables and objects . 37 11.3 Methods . 38 11.4 Reassigning a variable . 39 12 Basic Ruby - Ruby basics . 41 III Contents 13 Dealing with variables . 43 14 Program flow . 45 15 Writing functions . 47 16 Blocks . 49 17 Ruby is really, really object-oriented . 53 18 Basic Ruby - Data types . 55 18.1 Ruby Data Types . 55 18.2 Constants . 55 18.3 Symbols . 56 18.4 Hashes . 57 18.5 Arrays . 58 18.6 Strings . 62 18.7 Numbers (Integers and Floats) . 66 18.8 Additional String Methods . 67 19 Basic Ruby - Writing methods . 69 19.1 Defining Methods . 69 20 Basic Ruby - Classes and objects . 71 20.1 Ruby Classes . 71 20.2 Creating Instances of a Class . 71 20.3 Creating Classes . 71 20.4 Self . 72 20.5 Class Methods . 72 21 Basic Ruby - Exceptions . 75 22 Syntax - Lexicology . 77 22.1 Identifiers . 77 22.2 Comments . 77 22.3 Embedded Documentation . 77 22.4 Reserved Words . 78 22.5 Expressions . 78 23 Syntax - Variables and Constants . 79 23.1 Local Variables . 79 23.2 Instance Variables . 79 23.3 Class Variables . 80 23.4 Global Variables . 80 23.5 Constants . 80 23.6 Pseudo Variables . 81 23.7 Pre-defined Variables . 82 23.8 Pre-defined Constants . 85 23.9 Notes . 85 24 Syntax - Literals . 87 24.1 Numerics . 87 24.2 Strings . ..
Recommended publications
  • Events, Co-Routines, Continuations and Threads OS (And Application)Execution Models System Building
    Events, Co-routines, Continuations and Threads OS (and application)Execution Models System Building General purpose systems need to deal with • Many activities – potentially overlapping – may be interdependent • Activities that depend on external phenomena – may requiring waiting for completion (e.g. disk read) – reacting to external triggers (e.g. interrupts) Need a systematic approach to system structuring © Kevin Elphinstone 2 Construction Approaches Events Coroutines Threads Continuations © Kevin Elphinstone 3 Events External entities generate (post) events. • keyboard presses, mouse clicks, system calls Event loop waits for events and calls an appropriate event handler. • common paradigm for GUIs Event handler is a function that runs until completion and returns to the event loop. © Kevin Elphinstone 4 Event Model The event model only requires a single stack Memory • All event handlers must return to the event loop CPU Event – No blocking Loop – No yielding PC Event SP Handler 1 REGS Event No preemption of handlers Handler 2 • Handlers generally short lived Event Handler 3 Data Stack © Kevin Elphinstone 5 What is ‘a’? int a; /* global */ int func() { a = 1; if (a == 1) { a = 2; } No concurrency issues within a return a; handler } © Kevin Elphinstone 6 Event-based kernel on CPU with protection Kernel-only Memory User Memory CPU Event Loop Scheduling? User PC Event Code SP Handler 1 REGS Event Handler 2 User Event Data Handler 3 Huh? How to support Data Stack multiple Stack processes? © Kevin Elphinstone 7 Event-based kernel on CPU with protection Kernel-only Memory User Memory CPU PC Trap SP Dispatcher User REGS Event Code Handler 1 User-level state in PCB Event PCB Handler 2 A User Kernel starts on fresh Timer Event Data stack on each trap (Scheduler) PCB B No interrupts, no blocking Data Current in kernel mode Thead PCB C Stack Stack © Kevin Elphinstone 8 Co-routines Originally described in: • Melvin E.
    [Show full text]
  • 18-Variables.Pdf
    Mehran Sahami Handout #18 CS 106A October 12, 2007 Variables, variables, everywhere… Based on a handout by Patrick Young. Local Variables Local variables are created local to the method (or the block—see “Block Scope” section below) in which they are defined. They are destroyed when execution of the method has been completed. Local variables can only be accessed from within the method in which they are declared. Because of their transient nature, local variables cannot store persistent information about an object between method calls. Local Variables Example Consider, for example, the following snippet of code. class AnExample extends ConsoleProgram { public void methodOne { int a = readInt("Enter a: "); println("a = " + a); } public void methodTwo { int b = a; // BUG!: cannot refer to variable a in methodOne println("b = " + b); } } The variables a and b are local variables declared within different methods in the class AnExample . Because these variables are local variables, a can only be referred to within methodOne and variable b can only be accessed within methodTwo . Our attempt to initialize b using the value of a is illegal, as code in methodTwo cannot access local variables from methodOne or any other method. Because local variable values do not persist after their containing method has completed, the variable a will be destroyed when methodOne has completed execution. The next time methodOne is called, a new variable a will be created. Block Scope While we typically think of local variables as local to a particular method, in Java local variables are actually local to a block of code. While a method defines a block of code (since the opening and closing braces of the method define a block), for and while loops, if -statements, and other constructs are also considered blocks of code.
    [Show full text]
  • Chapter 5 Names, Bindings, and Scopes
    Chapter 5 Names, Bindings, and Scopes 5.1 Introduction 198 5.2 Names 199 5.3 Variables 200 5.4 The Concept of Binding 203 5.5 Scope 211 5.6 Scope and Lifetime 222 5.7 Referencing Environments 223 5.8 Named Constants 224 Summary • Review Questions • Problem Set • Programming Exercises 227 CMPS401 Class Notes (Chap05) Page 1 / 20 Dr. Kuo-pao Yang Chapter 5 Names, Bindings, and Scopes 5.1 Introduction 198 Imperative languages are abstractions of von Neumann architecture – Memory: stores both instructions and data – Processor: provides operations for modifying the contents of memory Variables are characterized by a collection of properties or attributes – The most important of which is type, a fundamental concept in programming languages – To design a type, must consider scope, lifetime, type checking, initialization, and type compatibility 5.2 Names 199 5.2.1 Design issues The following are the primary design issues for names: – Maximum length? – Are names case sensitive? – Are special words reserved words or keywords? 5.2.2 Name Forms A name is a string of characters used to identify some entity in a program. Length – If too short, they cannot be connotative – Language examples: . FORTRAN I: maximum 6 . COBOL: maximum 30 . C99: no limit but only the first 63 are significant; also, external names are limited to a maximum of 31 . C# and Java: no limit, and all characters are significant . C++: no limit, but implementers often impose a length limitation because they do not want the symbol table in which identifiers are stored during compilation to be too large and also to simplify the maintenance of that table.
    [Show full text]
  • 7. Functions in PHP – II
    7. Functions in PHP – II Scope of variables in Function Scope of variable is the part of PHP script where the variable can be accessed or used. PHP supports three different scopes for a variable. These scopes are 1. Local 2. Global 3. Static A variable declared within the function has local scope. That means this variable is only used within the function body. This variable is not used outside the function. To demonstrate the concept, let us take an example. // local variable scope function localscope() { $var = 5; //local scope echo '<br> The value of $var inside the function is: '. $var; } localscope(); // call the function // using $var outside the function will generate an error echo '<br> The value of $var inside the function is: '. $var; The output will be: The value of $var inside the function is: 5 ( ! ) Notice: Undefined variable: var in H:\wamp\www\PathshalaWAD\function\function localscope demo.php on line 12 Call Stack # Time Memory Function Location 1 0.0003 240416 {main}( ) ..\function localscope demo.php:0 The value of $var inside the function is: Page 1 of 7 If a variable is defined outside of the function, then the variable scope is global. By default, a global scope variable is only available to code that runs at global level. That means, it is not available inside a function. Following example demonstrate it. <?php //variable scope is global $globalscope = 20; // local variable scope function localscope() { echo '<br> The value of global scope variable is :'.$globalscope; } localscope(); // call the function // using $var outside the function will generate an error echo '<br> The value of $globalscope outside the function is: '.
    [Show full text]
  • Designing an Ultra Low-Overhead Multithreading Runtime for Nim
    Designing an ultra low-overhead multithreading runtime for Nim Mamy Ratsimbazafy Weave [email protected] https://github.com/mratsim/weave Hello! I am Mamy Ratsimbazafy During the day blockchain/Ethereum 2 developer (in Nim) During the night, deep learning and numerical computing developer (in Nim) and data scientist (in Python) You can contact me at [email protected] Github: mratsim Twitter: m_ratsim 2 Where did this talk came from? ◇ 3 years ago: started writing a tensor library in Nim. ◇ 2 threading APIs at the time: OpenMP and simple threadpool ◇ 1 year ago: complete refactoring of the internals 3 Agenda ◇ Understanding the design space ◇ Hardware and software multithreading: definitions and use-cases ◇ Parallel APIs ◇ Sources of overhead and runtime design ◇ Minimum viable runtime plan in a weekend 4 Understanding the 1 design space Concurrency vs parallelism, latency vs throughput Cooperative vs preemptive, IO vs CPU 5 Parallelism is not 6 concurrency Kernel threading 7 models 1:1 Threading 1 application thread -> 1 hardware thread N:1 Threading N application threads -> 1 hardware thread M:N Threading M application threads -> N hardware threads The same distinctions can be done at a multithreaded language or multithreading runtime level. 8 The problem How to schedule M tasks on N hardware threads? Latency vs 9 Throughput - Do we want to do all the work in a minimal amount of time? - Numerical computing - Machine learning - ... - Do we want to be fair? - Clients-server - Video decoding - ... Cooperative vs 10 Preemptive Cooperative multithreading:
    [Show full text]
  • Pexpect Documentation Release 4.8
    Pexpect Documentation Release 4.8 Noah Spurrier and contributors Apr 17, 2021 Contents 1 Installation 3 1.1 Requirements...............................................3 2 API Overview 5 2.1 Special EOF and TIMEOUT patterns..................................6 2.2 Find the end of line – CR/LF conventions................................6 2.3 Beware of + and * at the end of patterns.................................7 2.4 Debugging................................................8 2.5 Exceptions................................................8 2.6 Pexpect on Windows...........................................9 3 API documentation 11 3.1 Core pexpect components........................................ 11 3.2 fdpexpect - use pexpect with a file descriptor.............................. 23 3.3 popen_spawn - use pexpect with a piped subprocess.......................... 23 3.4 replwrap - Control read-eval-print-loops................................. 24 3.5 pxssh - control an SSH session...................................... 25 4 Examples 33 5 FAQ 35 6 Common problems 39 6.1 Threads.................................................. 39 6.2 Timing issue with send() and sendline()................................. 39 6.3 Truncated output just before child exits................................. 40 6.4 Controlling SSH on Solaris....................................... 40 6.5 child does not receive full input, emits BEL............................... 40 7 History 41 7.1 Releases................................................. 41 7.2 Moves and forks............................................
    [Show full text]
  • Ajuba Solutions Version 1.4 COPYRIGHT Copyright © 1998-2000 Ajuba Solutions Inc
    • • • • • • Ajuba Solutions Version 1.4 COPYRIGHT Copyright © 1998-2000 Ajuba Solutions Inc. All rights reserved. Information in this document is subject to change without notice. No part of this publication may be reproduced, stored in a retrieval system, or transmitted in any form or by any means electronic or mechanical, including but not limited to photocopying or recording, for any purpose other than the purchaser’s personal use, without the express written permission of Ajuba Solutions Inc. Ajuba Solutions Inc. 2593 Coast Avenue Mountain View, CA 94043 U.S.A http://www.ajubasolutions.com TRADEMARKS TclPro and Ajuba Solutions are trademarks of Ajuba Solutions Inc. Other products and company names not owned by Ajuba Solutions Inc. that appear in this manual may be trademarks of their respective owners. ACKNOWLEDGEMENTS Michael McLennan is the primary developer of [incr Tcl] and [incr Tk]. Jim Ingham and Lee Bernhard handled the Macintosh and Windows ports of [incr Tcl] and [incr Tk]. Mark Ulferts is the primary developer of [incr Widgets], with other contributions from Sue Yockey, John Sigler, Bill Scott, Alfredo Jahn, Bret Schuhmacher, Tako Schotanus, and Kris Raney. Mark Diekhans and Karl Lehenbauer are the primary developers of Extended Tcl (TclX). Don Libes is the primary developer of Expect. TclPro Wrapper incorporates compression code from the Info-ZIP group. There are no extra charges or costs in TclPro due to the use of this code, and the original compression sources are freely available from http://www.cdrom.com/pub/infozip or ftp://ftp.cdrom.com/pub/infozip. NOTE: TclPro is packaged on this CD using Info-ZIP’s compression utility.
    [Show full text]
  • Chapter 21. Introduction to Fortran 90 Language Features
    http://www.nr.com or call 1-800-872-7423 (North America only), or send email to [email protected] (outside North Amer readable files (including this one) to any server computer, is strictly prohibited. To order Numerical Recipes books or CDROMs, v Permission is granted for internet users to make one paper copy their own personal use. Further reproduction, or any copyin Copyright (C) 1986-1996 by Cambridge University Press. Programs Copyright (C) 1986-1996 by Numerical Recipes Software. Sample page from NUMERICAL RECIPES IN FORTRAN 90: THE Art of PARALLEL Scientific Computing (ISBN 0-521-57439-0) Chapter 21. Introduction to Fortran 90 Language Features 21.0 Introduction Fortran 90 is in many respects a backwards-compatible modernization of the long-used (and much abused) Fortran 77 language, but it is also, in other respects, a new language for parallel programming on present and future multiprocessor machines. These twin design goals of the language sometimes add confusion to the process of becoming fluent in Fortran 90 programming. In a certain trivial sense, Fortran 90 is strictly backwards-compatible with Fortran 77. That is, any Fortran 90 compiler is supposed to be able to compile any legacy Fortran 77 code without error. The reason for terming this compatibility trivial, however, is that you have to tell the compiler (usually via a source file name ending in “.f”or“.for”) that it is dealing with a Fortran 77 file. If you instead try to pass off Fortran 77 code as native Fortran 90 (e.g., by naming the source file something ending in “.f90”) it will not always work correctly! It is best, therefore, to approach Fortran 90 as a new computer language, albeit one with a lot in common with Fortran 77.
    [Show full text]
  • Automating Configuration N49(PDF)
    Automating Network Configuration Brent Chapman Netomata, Inc. [email protected] www.netomata.com NANOG 49 — 13 June 2010 Copyright © 2010, Netomata, Inc. All Rights Reserved. Introduction Who I am What I'm here to talk about 2 Copyright © 2010, Netomata, Inc. All Rights Reserved. Why automate network configuration? Because automated networks are More reliable Easier to maintain Easier to scale 3 Copyright © 2010, Netomata, Inc. All Rights Reserved. For example... Imagine you're managing a moderately complex web site Multiple real and virtual hosts Several "environments" (production, testing, development, etc.) Separate VLAN for each environment 4 Copyright © 2010, Netomata, Inc. All Rights Reserved. For example... What networking devices & services need to be managed? Routers Switches Load Balancers Firewalls Real-time status monitoring (i.e., Nagios) Long-term usage monitoring (i.e., MRTG) 5 Copyright © 2010, Netomata, Inc. All Rights Reserved. For example... How to add new virtual host to existing load balancer pool? Set up host itself, using Puppet or cfengine or whatever Add host to VLAN defs on switches Add host to ACLs on routers Add host to pool on load balancers Add host to NAT and ACLs on firewalls Add host to real-time monitoring (i.e., Nagios) Add host to usage monitoring (i.e., MRTG) 6 Copyright © 2010, Netomata, Inc. All Rights Reserved. For example... What's the problem with doing all that by hand? You have to remember how to manage all those very different devices (and you probably don't do it very often) It takes a lot of time Every step is a chance to make a mistake You might get distracted, and never finish Over time, these small mistakes add up, leading to inconsistent networks that are unreliable and difficult to troubleshoot 7 Copyright © 2010, Netomata, Inc.
    [Show full text]
  • A First Course to Openfoam
    Basic Shell Scripting Slides from Wei Feinstein HPC User Services LSU HPC & LON [email protected] September 2018 Outline • Introduction to Linux Shell • Shell Scripting Basics • Variables/Special Characters • Arithmetic Operations • Arrays • Beyond Basic Shell Scripting – Flow Control – Functions • Advanced Text Processing Commands (grep, sed, awk) Basic Shell Scripting 2 Linux System Architecture Basic Shell Scripting 3 Linux Shell What is a Shell ▪ An application running on top of the kernel and provides a command line interface to the system ▪ Process user’s commands, gather input from user and execute programs ▪ Types of shell with varied features o sh o csh o ksh o bash o tcsh Basic Shell Scripting 4 Shell Comparison Software sh csh ksh bash tcsh Programming language y y y y y Shell variables y y y y y Command alias n y y y y Command history n y y y y Filename autocompletion n y* y* y y Command line editing n n y* y y Job control n y y y y *: not by default http://www.cis.rit.edu/class/simg211/unixintro/Shell.html Basic Shell Scripting 5 What can you do with a shell? ▪ Check the current shell ▪ echo $SHELL ▪ List available shells on the system ▪ cat /etc/shells ▪ Change to another shell ▪ csh ▪ Date ▪ date ▪ wget: get online files ▪ wget https://ftp.gnu.org/gnu/gcc/gcc-7.1.0/gcc-7.1.0.tar.gz ▪ Compile and run applications ▪ gcc hello.c –o hello ▪ ./hello ▪ What we need to learn today? o Automation of an entire script of commands! o Use the shell script to run jobs – Write job scripts Basic Shell Scripting 6 Shell Scripting ▪ Script: a program written for a software environment to automate execution of tasks ▪ A series of shell commands put together in a file ▪ When the script is executed, those commands will be executed one line at a time automatically ▪ Shell script is interpreted, not compiled.
    [Show full text]
  • PHP 8.0.2 - Phpinfo() 2021-02-23 14:53
    PHP 8.0.2 - phpinfo() 2021-02-23 14:53 PHP Version 8.0.2 System Linux effa5f35b7e3 5.4.83-v7l+ #1379 SMP Mon Dec 14 13:11:54 GMT 2020 armv7l Build Date Feb 9 2021 12:01:16 Build System Linux 96bc8a22765c 4.15.0-129-generic #132-Ubuntu SMP Thu Dec 10 14:07:05 UTC 2020 armv8l GNU/Linux Configure Command './configure' '--build=arm-linux-gnueabihf' '--with-config-file-path=/usr/local/etc/php' '--with-config-file-scan- dir=/usr/local/etc/php/conf.d' '--enable-option-checking=fatal' '--with-mhash' '--with-pic' '--enable-ftp' '--enable- mbstring' '--enable-mysqlnd' '--with-password-argon2' '--with-sodium=shared' '--with-pdo-sqlite=/usr' '--with- sqlite3=/usr' '--with-curl' '--with-libedit' '--with-openssl' '--with-zlib' '--with-pear' '--with-libdir=lib/arm-linux-gnueabihf' '- -with-apxs2' '--disable-cgi' 'build_alias=arm-linux-gnueabihf' Server API Apache 2.0 Handler Virtual Directory Support disabled Configuration File (php.ini) Path /usr/local/etc/php Loaded Configuration File /usr/local/etc/php/php.ini Scan this dir for additional .ini files /usr/local/etc/php/conf.d Additional .ini files parsed /usr/local/etc/php/conf.d/docker-php-ext-gd.ini, /usr/local/etc/php/conf.d/docker-php-ext-mysqli.ini, /usr/local/etc/php/conf.d/docker-php-ext-pdo_mysql.ini, /usr/local/etc/php/conf.d/docker-php-ext-sodium.ini, /usr/local/etc/php/conf.d/docker-php-ext-zip.ini PHP API 20200930 PHP Extension 20200930 Zend Extension 420200930 Zend Extension Build API420200930,NTS PHP Extension Build API20200930,NTS Debug Build no Thread Safety disabled Zend Signal Handling enabled
    [Show full text]
  • Java Static Keyword
    This page was exported from - TechnicalStack Export date: Sun Sep 26 13:56:23 2021 / +0000 GMT Java static keyword Java static keyword The static keyword in java is used for memory management mainly. We can apply java static keyword with variables, methods, blocks and nested class. The static keyword belongs to the class than instance of the class. The static can be: - variable (also known as class variable) - method (also known as class method) - block - nested class 1) Java static variable If you declare any variable as static, it is known static variable. - The static variable can be used to refer the common property of all objects (that is not unique for each object) e.g. company name of employees,college name of students etc. - The static variable gets memory only once in class area at the time of class loading. Advantage of static variable It makes your program memory efficient (i.e it saves memory). Understanding problem without static variable class Student{ int rollno; String name; String college="ITS"; } Suppose there are 500 students in my college, now all instance data members will get memory each time when object is created.All student have its unique rollno and name so instance data member is good.Here, college refers to the common property of all objects.If we make it static,this field will get memory only once. Java static property is shared to all objects. Example of static variable //Program of static variable class Student8{ int rollno; String name; static String college ="ITS"; Student8(int r,String n){
    [Show full text]