If you would like to star as a guest writer on Talented blog and share your knowledge on the (tech)topic of your choice, tell us at hello@talented.fi
Ruby was created in 1993 by Yukihiro Matsumoto (Matz). It’s a programming language that was designed to maximize programmers’ happiness.
Ruby is a language where term “flexible syntax” gets a new meaning. It’s a dynamically typed object-oriented language with a really loose syntax, so it can be bent further than the spoon in Matrix movie trilogy.
BLOCKS
Ruby has a specific way for defining a code block. You can use do
and end
or { }
to define a block.
["Teemu", "Paul", "Wayne"].each do |name|
puts "#{name} scores!"
end
The code inside the block is run only if File.open
creates the file successfully.
File.open(“basic_rules_of_secret_societies.txt”, “w”) do |file|
file.puts("1. Talented is building a secret society of experienced programmers")
file.puts("2. Goto 10")
end
You can call a block from a function.
class Person
attr_accessor :name, :email, :role
def initialize(role = :visitor)
self.role = role
yield(self)
end
end
Person.new do |person|person.name = “Tuomas”
person.email = “tuomas@localhost”
end
=> #<Person:0x007ffe660fa980 @name=”Tuomas”, @email=”tuomas@localhost” @role=:visitor>
ENUMERABLES
arr = ["Tuomas", "Maria", "Teemu", "Jasmin"]
reversed = arr.map { |s| s.reverse }
=> ["samouT", "airaM", "umeeT", "nimsaJ"]
secret_password = reversed.join()
=> "samouTairaMumeeTnimsaJ"
Filtering data structures without any side effects.
frameworks = {
"Ruby": ["Ruby on Rails", "Sinatra"],
"JavaScript": ["Express"],
"Python": ["Flask", "Django"]
}
# longer versionframeworks.select do |key, values|
values.count > 1
end
=> {:Ruby=>[“Ruby on Rails”, “Sinatra”], :Python=>[“Flask”, “Django”]}
# shorter versionframeworks.select {|k,v| v.count > 1}
=> {:Ruby=>[“Ruby on Rails”, “Sinatra”], :Python=>[“Flask”, “Django”]}
EVERYTHING IS AN OBJECT
if user.last_activity_at > 10.days.ago
UserMailer.lure_back(user).deliver_later
end
Number is an object and it can have methods.
irb(main):001:0> 3.class
=> Fixnum
irb(main):002:0> 3.to_s
=> "3"
irb(main):003:0> 3.to_f
=> 3.0
LEARN MORE
- Why’s Poignant Guide to Ruby (most likely the craziest programming guide)
- Free Ruby Screencasts from RubyTapas
- Interactive Ruby Tutorial