Skip to content

Instantly share code, notes, and snippets.

@tuomasj
Last active February 9, 2018 12:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tuomasj/7befd859d17d96fe93ec283a28e11279 to your computer and use it in GitHub Desktop.
Save tuomasj/7befd859d17d96fe93ec283a28e11279 to your computer and use it in GitHub Desktop.

Three Cool Things about Ruby

Ruby was created in 1993 by Yukihiro Matsumoto (Matz). It’s a programming language that was designed to maximise 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 version
frameworks.select do |key, values|
  values.count > 1
end
=> {:Ruby=>["Ruby on Rails", "Sinatra"], :Python=>["Flask", "Django"]}

# shorter version
frameworks.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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment