I'm currently learning Ruby to improve my Jekyll blog. At the moment, I can't really say if I like Ruby.
Just like PHP and Python, Ruby is implicitly typed. This means you can do the following:
# A list
a = [1,2,3,4,5]
# An integer
b = 42
# A floating point number
c = 3.141
Ruby is also dynamically typed:
a = 42
a = "now a is a string!"
One thing that is pretty annoying is the usage of begin ... end
.
I thought LaTeX was the only "language" in use that had this syntax.
Syntax examples
If, else if, else
a = 1
if a == 1 || a % 2 == 0
puts "a equals 1 or is even"
elsif a == 3
puts "a equals 3"
else
puts "a does not equal 1 or 3 and is not even"
end
String manipulation
String manipulation is weird in Ruby. Take a look at the last example. What would you expect?
s = "0123456789"
puts s[2..4]
puts s[2..s.length()]
puts s[2..-2]
Output is:
234
23456789
2345678
Now what would you expect to happen with "0123456789"[2..4]
?
I would expect Ruby to give "234"
. But this one actually fails.
Dictionaries
Dictionaries, which are sometimes also called 'maps' or 'associative arrays' are a neat data structure. Ruby uses this syntax:
dictionary = {"a"=> 7, "b"=> "x"}
if dictionary.has_key?("a")
puts "key 'a' is in dictionary! It is " + dictionary["a"].to_s
dictionary["a"] = 42
puts "Now it is " + dictionary["a"].to_s
puts dictionary.size()
puts dictionary.length()
puts dictionary.count()
end
map
myList = [1,2,3,4,5]
x = myList.map{|element| [element,element+1]}
x.each do |a, b|
puts "a: " + a.to_s + ", b: " + b.to_s
end
will print
a: 1, b: 2
a: 2, b: 3
a: 3, b: 4
a: 4, b: 5
a: 5, b: 6
.count(), .length(), .size()
At a first glance, those three seem to be aliases. But .count()
is not quite the same as .length()
and .size()
(source).
Blocks
A very interesting idea in Ruby is that of blocks. It seems to be similar to Pythons decorators:
def time_method(method=nil, *args)
beginning_time = Time.now
if block_given?
yield
else
self.send(method, args)
end
end_time = Time.now
puts "Time elapsed #{(end_time - beginning_time)*1000} milliseconds"
end
time_method do
(1..10000).each { |i| i }
end
Logging
Logging in Ruby is very convenient. See Logger Documentation
Notable libraries and projects
Nokogiri: Parsing HTML
The following code will parse yourHTMLcode
and select all a
-tags
(also known as links):
require 'nokogiri'
doc = Nokogiri::HTML.parse(yourHTMLcode)
links = doc.css('a').map { |link| [link['href'],link.text] }
links.each do |link, linktext|
puts "Link '"+link+"' was used with '"+linktext+"'"
end
Sequel
This way you can select elements from a SQLite-Database:
require 'sequel'
db = Sequel.sqlite("search.db")
rows = db.fetch( "SELECT rowid FROM pages WHERE url='/imprint';" ).all
#puts rows
#puts rows.count()
puts rows[0][:rowid]
See also: