1 / 29

Ruby

Ruby. and other languages… . Valuable Reference. The Ruby Programming Language, Flanagan & Matsumoto (creator of Ruby). What do you need to know about a new language?. How to execute Program structure Variables name, keywords, binding, scope, lifetime Data types type system

allene
Download Presentation

Ruby

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. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Ruby and other languages…

  2. Valuable Reference The Ruby Programming Language, Flanagan & Matsumoto (creator of Ruby)

  3. What do you need to know about a new language? • How to execute • Program structure • Variables • name, keywords, binding, scope, lifetime • Data types • type system • primitives, strings, arrays, hashes • pointers/references • type conversions and equality • Expressions • Operators, overloading, booleans, short-circuiting, conditional expression • Referential transparency • Statements vs Expressions • Control flow • conditionals • loops • Functions • Classes • Exception handling • Other features • Threads • Reflection • Libraries • Functional Language – other aspects, covered later • QUICK EX: With a partner • how do you learn a new programming language? • What types of programs do you write?

  4. Think like a compiler • Tokens: • int • count • = • 20 • ; • Grammar: • Based on BNF • Scanner (lexical analyzer): identifies the tokens of a program statement • Parser (syntax analyzer): determines whether the statement is valid, based on the language definition/grammar • int count = 20;

  5. Ruby Program Structure Expression vs statement? Basic unit is expression Primary expressions: true, false, nil, self, number and string literals, variable references (all represent values) Expressions: arithmetic, boolean Methods Classes Modules

  6. Get started - interactive • open IRB • puts “say Hi” say Hi • nil • nil is return… ruby has expressions, not statements

  7. Ruby Statement Structure Compare to Java/C++/Python * think: how does interpreter recognize tokens/statement? • Whitespace: mostly ignored • Statement separators: newline • use caution if statement doesn’t fit on one line • insert newline after operator, period or comma • OR escape the newline *

  8. Ruby Comments # This is a comment OR =begin This is a longer comment. =begin/=end must be at the start of a line =end

  9. Ruby Methods Compare to Java/C++/Python • No ( ) needed for function invocation • if use (), don’t put space after fn name! • f(3+2)+1 != f (3+2)+1 • Try it: “hello”.center 20 “hello”.delete “lo” • What’s good practice? Here are some thoughts: • http://stackoverflow.com/questions/340624/do-you-leave-parentheses-in-or-out-in-ruby

  10. Block Structure block surrounded by { } often call this the “body” never delimit with { } block delimited by “end” Compare to Java/C++ 10.times { puts “hello” } x = 5 unless x == 10 print x end • Blocks can be nested. Indent for clarity.

  11. Variables Compare to Java/C++/Fortran • length: no limit (afaik) • valid characters: • letters, numbers, _ • can’t start with number • $ used as first character of global var • @/@@ used to identify instance and class variables • ? (convention) end method name with ? if returns boolean • ! (convention) end method name with ! if dangerous • = used to make assignments (covered with classes) • no other punctuation • support for Unicode • first letter (enforced by ruby): • Constants, classes and modules begin with A-Z • case sensitive

  12. Keywords vs Reserved Words Compare to Java/C++ many words have special meaning (e.g. if, true, def, etc.) Keyword: has special meaning, but can be used as variable name Reserved: can’t be used as variable Ruby: keyword… can prefix with @, @@ or $ and use as variable name

  13. The Concept of Binding • A binding is an association, such as: • bind type of variable • bind operation to symbol (e.g., meaning of *) • bind function to its definition • Binding timeis the time at which a binding takes place. • Type binding • may be static or dynamic • explicit or implicit

  14. Possible Binding Times Language design time -- bind operator symbols to operations : sum = sum + count Language implementation time-- bind type to a representation : int => number of bits, etc. Compile time -- bind a variable to a type: int count; Link time – bind library subprogram to code: cout << x; Load time -- bind a FORTRAN 77 variable to a memory cell (or a C static variable) Runtime-- bind a nonstatic local variable to a memory cell

  15. Static vs. Dynamic Binding A binding is static if it first occurs before run time and remains unchanged throughout program execution. A binding is dynamic if it first occurs during execution or can change during execution of the program NOTE: doesn't consider paging etc. which is at the hardware level

  16. Dynamic Type Binding How are generic program units done in C++? Java? • Type not specified by declaration, not determined by name (JavaScript, PHP, Ruby) • Specified through an assignment statement list = [2, 4.33, 6, 8]; list = 17.3; • Advantage: flexibility (generic program units) • Disadvantages: • High cost (dynamic type checking requires run-time descriptors, normally interpreted) • Type error detection by the compiler is difficult

  17. Quick Exercise How would dynamic types be implemented? What data structure(s) would you use? How does this impact your code – consider efficiency, reliability. Specifically, think about implementing +, where 3 + 5 is 8 and “hello” + “ world” is “hello world” Turn in for class participation (no specific format, just show some thought)

  18. Dynamic Type Issue i = x; // desired, x is scalar i = y; // typed accidentally, y is array

  19. Explicit/Implicit Declaration • An explicit declarationis a program statement used for declaring the types of variables: int count; • An implicit declarationis a default mechanism for specifying types of variables (the first appearance of the variable in the program) • Both create static bindings to types (i.e., type doesn’t change during execution of program) • FORTRAN, PL/I, BASIC, and Perl provide implicit declarations • Advantage: writability • Disadvantage: reliability • Perl: @ is array, % is hash, $ is scalar • Fortran: I-N integer, others single precision, can override

  20. Ruby Data Types: numbers C++ has unsigned ints, Java does not… concept doesn’t apply to Ruby – why? COBOL was for business… inherent big decimal. Java/C# provide. C++ does not. Adv: accuracy. Disadv: waste space • Numeric • Integer – allows base 8, 16, 2 (binary) • Fixnum: fit in 31 bits • Bignum: arbitrary size • Float – includes scientific notation • Complex • BigDecimal: use decimal rather than binary rep • Rational

  21. A few details -7/3 = -3 in Ruby, -2 in Java/C++ div = integer division, e.g., 7.div 3 fdiv = floating point division, e.g., 7.fdiv 3 quo = rational division Float::MAX Infinity Numbers are immutable (as you’d expect)

  22. Ruby Data Types: strings Other languages with interpolation? • String literals – single quote • ‘A ruby string’ • ‘Didn\’t you have fun?’ • Only escape \’ or \\ • newlines are embedded if multi-line • String literals – double quote • normal escape sequences (\t, \n etc) • string interpolation w=5 h=4 puts "The area is #{w*h}"

  23. More strings Java converts right-hand to string, Ruby doesn’t • Strings are mutable in Ruby • + is concatenation (often prefer interpolation) age = 32 puts "I am " + age.to_s • << is append s = "Hello" s << " World" puts s • Extract characters puts s[0, 5] • * repeats text puts "hey " * 5

  24. Characters Python also has strings of length 1, not primitive chars Does Java support unicode? Does C++? • Changed from Ruby 1.8 to Ruby 1.9 • Characters are now strings of length 1 • Not covered • multi-byte characters (need for unicode… 16-bit encoding, first 128 the same as ASCII) • specify encodings (e.g., ASCII-8BIT, BINARY, US-ASCII, ASCII, ISO-8859-15, UTF-8) • many other String methods, such as downcase, upcase, chop, delete, tr, etc.

  25. Program Execution • Ruby is a scripting language • No special main method • In general, script starts executing with line 1, continues until all lines executed • Methods/classes come into existence when they are read in the file • May use BEGIN/END (not common to do) • BEGIN { # global init code ] • END { #global shutdown code] • if multiple BEGINS, interpreter executes in order read

  26. Getting started – command line Open text editor puts “say Hi” save file as demo1.rb at command line: ruby demo1.rb

  27. String Access: Quick Exercise Compare to C/C++ • Can use [] with: • [ix] • [ix,len] • [ix..ix] • [-ix] • stringname.length, etc. • if index too large, just returns nil • Try: • s = "Sunday, Monday, Tuesday, Wednesday, Thursday, Friday" • Find different ways to extract Sunday, Monday and Friday using the index options shown above • Use different ways to modify the string (e.g., convert the string to: Monday, day, Tuesday, Wednesday, Thursday, Saturday) • Nothing to submit; no right answers – just play!

  28. Get started Do Ruby Intro homework

  29. Topic Summary • Language concepts • Effect of syntax on compilation • Binding • overview • static vs dynamic • explicit vs implicit types • Scripting language • Keywords vsReserved words • Ruby Basics • program structure • program execution • block structure • methods • comments • variables • strings • interpolation • numbers

More Related