Quick Guide to Ruby

Introduction

Ruby is an open-source, cross-platform, command line-based language that's lighter than Python and completly object-oriented.

To Read

DONE https://www.ruby-lang.org/en/documentation/

The Little Book Of Ruby Programming: Learn To Program Ruby For Beginners 2019

Variables beginning with the @ character are ‘instance variables’ – that means that they belong to individuals objects – or ‘instances’ of the class. It is not necessary to pre-declare variables:

class Dog
    def set_name( aName )
        @myname = aName
    end
end

When a class contains a method named initialize this is automatically called when an object is created using the new method.

The inspect method is defined for all Ruby objects. It returns a string containing a human-readable representation of the object.

Class is the definition; object is an instance of a class.

To read/write a class attribute/property:

def description
    return @description
end
 
def description=( aDescription )
    @description = aDescription
end

… or even simpler:

class Thing
    #a symbol is a name preceded by a colon
    attr_reader :description
    attr_writer :description
    # some methods here…
end

… or even simpler˛:

class Thing
    attr_accessor :value
end

Note: Calling attr_reader/attr_accessor with a symbol actually creates a variable with the same name as the symbol. For instance, "attr_accessor :name" creates a @name variable.

@name is an instance variable, while @@name is a class variable (all objects derived from a specific class share the same class variables.)

 

DONE Ruby For Beginners: Your Guide To Easily Learn Ruby Programming in 7 days iCodeAcademy 2017

In Ruby, you must write constants in uppercases. Ruby permits changing the value of constants; However, Ruby will give you a warning regarding the constant variable having a previous declaration.

Variable identifiers are case sensitive.

Global variables in the entire program always starts with a dollar sign ($) immediately followed by a variable name.   

The scope of a class variable is limited to the class they were defined or declared. The class variable name always starts with '@@', eg. @@length = 20 . Aside from the class itself, these variables are also accessible by class instances. You need to initialize the class variables at the class level. Their values can be altered using instance or class methods.

The scope of instance variable is limited only to a certain instance of a class. The instance variable always starts with '@' immediately followed by the variable name: @rem = 'Use me throughout the instance of this class'.
It is best not to use instance variables at this point in time, unless you fully grasp everything that you need to know about Ruby instance.

The local variable does not need any special character before its name: num1 = 20 .

When using do/end blocks, you can use { } if the entire expression can fit within a single line:

[1, 2, 3].each { |i| # do things }

You must capitalize the first letter of each word when naming your class, eg. "class TheInitialClass".

In Ruby, procedures are called methods:

# yo.rb
def yo(texts='hello')
  puts texts + '.' 
end
 
yo("hi")
yo "hi" #Both work

In Ruby, each method naturally returns an evaluated result of the latest executed line:

list = [1, 2, 3, 4, 5]
def transform(array)
  array.pop
end

But you can specify return (what's the point, since instructions thereafter aren't run?):

def added(num)
  return num + 2
  num + 5 #ignored
end

How to chain a method:

def add_four(num)
  num + 4
end
 
add_four(3).times { puts 'Print 7 times' } #prints this seven times (3+4).times

The ternary operator:

true ? "this is okay" : "this is bad"

Note that the question mark is a valid character at the end of a method name: As a code style convention, it indicates that a method returns a boolean value:

if z.odd?
    puts z
end

Beginning Ruby- From Novice to Professional, 3rd ed. - Cooper (Apress, 2016, 9781484212790, eng).pdf

Ruby Essentials 2012 Neil Smyth

Learn Ruby The Hard Way

Eloquent.Ruby - Feb.2011 - Russ Olsen.pdf

Sams Teach Yourself Ruby in 21 Days - 2002

Programming Ruby - The Pragmatic Programmer's Guide 2001

Q&A

What's difference between "doc=" and "@doc="?

Variable scope.

https://www.techotopia.com/index.php/Ruby_Variable_Scope

https://www.rubyguides.com/2019/03/ruby-scope-binding/

What files do I need to run a script with no extra modules?

c:\Ruby27\files.txt

Setup

The Ruby installer is available in two forms: A 10MB package with basic features on Windows; Downloading and compiling extra modules requires installing the full Ruby+Devkit for a total of ~125MB.

Ruby's package manager is called RubyGems is. A Ruby package is called a "gem" and can easily be installed via the command line.

irb is the interactive command-line interpreter while ruby(w).exe runs scripts.

Code Snippets

Running Ruby scripts

  1. Open a terminal window
  2. ruby myscript.rb (or type "myscript.rb", provided Windows is configured to match that extension with Ruby's interpreter)

Running live Ruby instructions

Open a terminal window, and type "irb"

Commenting

# oneline

=begin

A whole block of code

=end

Concatenating strings

https://www.rubyguides.com/2019/07/ruby-string-concatenation/

Checking the number of input parameters

if ARGV.length != 1

    puts "Usage: ruby #{__FILE__} myarg"

    exit(true)

else

    puts ARGV[0]

end

Looping through files

Dir.glob(ARGV[0]) do |file|

  puts file

end

Checking if file exists

if not (File.file?('myapp.exe'))

        puts 'Error: myapp.exe not found'

        exit(true)

end

Prompting user and displaying a string

puts "What is your name:"

option = gets.chomp

Formating a string

time = 5
message = "Processing of the data has finished in %d seconds" % [time]

Alternatively:

print(sprintf("Hello, %s", "World"))

Creating a simple array

a = [1, 'hi']

puts a[0]

a.each {|item| puts item }

Creating and looping through an associative array (hash)

options = {1 => "item1", 2 => "item2"}

options.each do |key, value|

    puts "#{key}. #{value}"

end

Case/end

case option

    when "1"

        puts "You chose option 1"    

    when "2"

        system('some.exe someswitch')

    else

      print "Unknown option: #{option}"

end

Extract text with a regex

https://www.rubyguides.com/2015/06/ruby-regex/

pm = text.match(/<Placemark>.+<\/Placemark>/m)

puts pm

Substitute text

Using a string

str = "white chocolate"

str.gsub("white", "dark")

Using a regex

text = text.gsub(/(<Some>)/,'</Blah>\1')

puts text

Reading/writing files

The whole thing

text = File.read("input.txt")

Line by line

File.readlines('file.txt').each do |line|

    puts line

end

Write

File.open('file.txt', 'w') do |file|

    file.puts 'Wrote some text.'

end

Run an external application

https://www.rubyguides.com/2018/12/ruby-system/

https://stackoverflow.com/questions/2232/how-to-call-shell-commands-from-ruby/37329716#37329716

COMMAND = "c:\\tidy.exe -utf8 -indent -xml -o %s %s" % ["output.txt", "input.txt"]

puts COMMAND

#Returns true if the command was found and run successfully, false otherwise.

result = system( COMMAND )

if result

        puts "Command ran OK"

else

        puts "Command failed"

end

Parsing XML files with Nokogiri

What is XML?

A Really, Really, Really Good Introduction to XML

Basically, a DTD (document type definition) provides instructions about the structure of your particular XML document. It’s a lot like a rule book that states which tags are legal, and where.

What is Nokogiri?

Nokogiri is a DOM/SAX parser that supports searching with XPath/CSS. It offers better performance than REXML. A Ruby gem that wraps libxml2.

https://www.rubydoc.info/github/sparklemotion/nokogiri/index

Nokogiri's css method allows us to target individual or groups of HTML methods using CSS selectors [meant specifically for HTML, or XPath which is more universal). No worries if you're not an expert on CSS. It's enough to recognize the basic syntax. "Nokogiri's css method will serve most of your needs. For webpages that require more precise selectors, you can jump into the world of XPath syntax and utilize Nokogiri's xpath method. XPath can handle certain kinds of selections more gracefully than CSS selectors."

Help

https://groups.google.com/g/nokogiri-talk

https://github.com/sparklemotion/nokogiri/wiki/Cheat-sheet

TO READ

DONE https://nokogiri.org/

https://nokogiri.org/tutorials/toc.html

https://www.w3schools.com/xml/xpath_intro.asp

Setup

It is not part of the basic Windows package, and must be installed through gem: gem install nokogiri

If it fails installing, uninstall the Ruby package and downgrade, or ask for support (mailing list).

Usage

https://nokogiri.org/tutorials/searching_a_xml_html_document.html

The Node methods xpath and css actually return a NodeSet, which acts very much like an array, and contains matching nodes from the document. If you know you're going to get only a single result back, you can use the shortcuts at_css and at_xpath instead of having to access the first element of a NodeSet [@doc.at_css("item") instead of @doc.css("item").first].

You do not have to use XPath to get the benefits of namespaces. CSS selectors can be used as well. CSS just uses the pipe symbol to indicate a namespace search: @doc.css('xmlns|title').

Reading + editing a KML file

require "nokogiri"
 
doc = Nokogiri::XML(File.read "input.kml")
 
#Who needs namespaces?
doc.remove_namespaces!
 
name_node = doc.at_xpath("/kml/Document/name")
name_node.content = "New Document Name"
 
placemarks_with_linestring = doc.xpath("//Placemark[LineString]")
#Add an element to all blocks that contain a LineString
placemarks_with_linestring.each do |placemark|
  placemark.add_child "<some>blah</some>"
end
 
File.open("output.kml", "w") do |file|
  file.write doc.to_xml
end

Q&A

@doc vs. doc: Scope.

CSS vs. XPath?

at_ ? h1 = @doc.at_css "h1"

namespace? "We would not be able to deal with colliding tag names without namespaces."

Infos

https://tenderlovemaking.com/2009/04/23/namespaces-in-xml.html

Resources