Home |
Last modified: 07-12-2021 |
Ruby is an open-source, cross-platform, command line-based language that's lighter than Python and completly object-oriented.
DONE https://www.ruby-lang.org/en/documentation/
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:
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:
… or even simpler:
… or even simpler˛:
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.)
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:
You must capitalize the first letter of each word when naming your class, eg. "class TheInitialClass".
In Ruby, procedures are called methods:
In Ruby, each method naturally returns an evaluated result of the latest executed line:
But you can specify return (what's the point, since instructions thereafter aren't run?):
How to chain a method:
The ternary operator:
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:
Ruby Essentials 2012 Neil Smyth
Eloquent.Ruby - Feb.2011 - Russ Olsen.pdf
Sams Teach Yourself Ruby in 21 Days - 2002
Programming Ruby - The Pragmatic Programmer's Guide 2001
Variable scope.
https://www.techotopia.com/index.php/Ruby_Variable_Scopehttps://www.rubyguides.com/2019/03/ruby-scope-binding/
c:\Ruby27\files.txt
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.
Open a terminal window, and type "irb"
# oneline
=begin
A whole block of code
=end
if ARGV.length != 1
puts "Usage: ruby #{__FILE__} myarg"
exit(true)
else
puts ARGV[0]
end
Dir.glob(ARGV[0]) do |file|
puts file
end
if not (File.file?('myapp.exe'))
puts 'Error: myapp.exe not found'
exit(true)
end
puts "What is your name:"
option = gets.chomp
time = 5
message = "Processing of the data has finished in %d seconds"
% [time]
Alternatively:
print(sprintf("Hello, %s", "World"))
a = [1, 'hi']
puts a[0]
a.each {|item| puts item }
options = {1 => "item1", 2 => "item2"}
options.each do |key, value|
puts "#{key}. #{value}"
end
case option
when "1"
puts "You chose option 1"
when "2"
system('some.exe someswitch')
else
print "Unknown option: #{option}"
end
pm = text.match(/<Placemark>.+<\/Placemark>/m)
puts pm
str = "white chocolate"
str.gsub("white", "dark")
text = text.gsub(/(<Some>)/,'</Blah>\1')
puts text
text = File.read("input.txt")
File.readlines('file.txt').each do |line|
puts line
end
File.open('file.txt', 'w') do |file|
file.puts 'Wrote some text.'
end
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
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.
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/indexNokogiri'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."
https://github.com/sparklemotion/nokogiri/wiki/Cheat-sheet
https://www.w3schools.com/xml/xpath_intro.asp
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).
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').
@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."