Introduction

Table of Contents


From wikipedia)

Ruby is a dynamic, reflective, object-oriented, general-purpose programming language. It was designed and developed in the mid-1990s by Yukihiro "Matz" Matsumoto in Japan. According to the creator, Ruby was influenced by Perl, Smalltalk, Eiffel, Ada, and Lisp. It supports multiple programming paradigms, including functional, object-oriented, and imperative. It also has a dynamic type system and automatic memory management


Installation


Hello World example

  • Let's start with simple a Ruby program and how to run it
  • Use your favorite text editor to open a new file, type puts 'hello there!' and save the file as hello.rb
    • puts writes content of objects and adds a newline if not already present
    • in this example, it gets written to stdout
  • Running it is as simple as invoking ruby command and passing hello.rb as argument
$ cat hello.rb
puts 'hello there!'

$ ruby hello.rb
hello there!
  • An alternate way to run is using shebang)
  • the # character indicates start of comment in Ruby
  • if # is followed by ! in first line of the program, then it becomes a shebang
$ type env ruby
env is /usr/bin/env
ruby is /usr/local/bin/ruby

$ cat hello_world.rb
#!/usr/bin/env ruby

puts 'Hello World'

$ chmod +x hello_world.rb
$ ./hello_world.rb
Hello World

Further Reading


Ruby REPL

  • It is generally used to execute snippets of Ruby language as a means to learning Ruby or for debugging purposes
  • Result of entered expression is displayed with a prefix =>
    • also, a special variable _ holds the result of last expression in the interactive session
  • use exit to end the interactive session
  • comments will be used within code snippets presented in this material to add relevant information
$ # puts always returns nil
$ irb
irb(main):001:0> puts 'hi'     
hi
=> nil
irb(main):002:0> exit
  • irb can be customized in many ways, see document link for details
  • here on, irb --simple-prompt will be used for simplicity
$ alias irb='irb --simple-prompt'

$ irb
>> num = 5
=> 5
>> num
=> 5
>> 3 + 4
=> 7
>> 12 + _
=> 19
>> exit
  • Often, you'd want to re-use previous instructions or correct a mistake
  • On Linux, you need to install the rb-readline extension module. Invoking irb after that will allow arrow keys for navigation, ctrl+r for search, etc
    • If you are not using environment manager like RVM, use gem install --user-install rb-readline

Further Reading

results matching ""

    No results matching ""