Ruby: First Steps

(Ruby の初歩)

3rd lecture, April 22, 2019

Projects in Information Technology II

http://www.sw.it.aoyama.ac.jp/2019/Projects2/lecture3.html

Martin J. Dürst

AGU

© 2019 Martin J. Dürst 青山学院大学

ミニテスト

 

Today's Schedule

 

Course Overview

 

Last Week's Exercise 2a:
A Stylesheet for Last Weeks' Documents

 

Last Week's Exercise 2b:
A Stylesheet for Ruby Documentation

You can use your stylesheet in the Ruby documentation on your notebook computer!

 

Last Week's Homework

  

Course Overview

 

Greetings from RubyKaigi

 

Ruby "Sales Points"

 

Comparison: C and Ruby

C Ruby
// greatest common denominator
int gcd(int a, int b)
{
    int r;
    if (a > b)
        r = gcd(a-b, b);
    else if (a < b)
        r = gcd(b-a, a);
    else
        r = a;
    return r;
}
# greatest common denominator
def gcd a, b
  if a > b
    r = gcd a-b, b
  elsif a < b
    r = gcd b-a, a
  else
    r = a
  end
  r
end

 

Differences

  1. Comments: // vs. #
  2. Function definition starts with def
  3. No (, ) around parameters in function definition (*)
  4. No type indications (int,…)
  5. No variable declarations (*)
  6. Indent usually 2 spaces
  7. No (, ) around conditions in if statement
  8. No (, ) around parameters in function calls (*, **)
  9. No ; at end of line (*)
  10. else if vs. elsif
  11. end to end if and def
  12. No return (*, **, last value is returned)

(*) Okay to keep them, but not very Ruby-like

(**) Sometimes necessary

 

Basic Types

 

Operators

 

Conversions

 

Classes

 

A Class Example

class Length
  def initialize
    @mm = 0.0
  end

  def mm; @mm; end

  def in # inches
    @mm * 25.4
  end

  def mm= milli
    @mm = milli
  end

  def in= inch
    @mm= inch / 25.4
  end
end

 

Names in Ruby

 

Input and Output

 

Program Example

while line = gets
  n = line.to_i
  puts "The square of " + n.to_s + " is " + (n*n).to_s
end

 

Testing

 

Exercise 3a: Calendar Conversion

 

Exercise 3b: Temperature Conversion

 

Using Moodle Q&A

 

Homework