Skip to content

Instantly share code, notes, and snippets.

@rodrigoflores
Created April 25, 2012 17:35
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save rodrigoflores/2491536 to your computer and use it in GitHub Desktop.
Save rodrigoflores/2491536 to your computer and use it in GitHub Desktop.
Ruby examples

Integers

1 + 1
2 * 2
5 / 3
5 % 3
5 ** 2

String

"Hi"
'Hi'
"My age is #{1+2}"
puts "Hi"
printf("%d", 2+2)

Boolean

true
false
nil

false and nil are falsy, everything else is truthy

if, unless, until, while, case

if x == 1
  puts "X é 1"
else
  puts "X não é 1"
end
unless x == 0
  puts "X não é 0"
else
  puts "X é 0"
end
message = case grade
when "A"
  puts "Congratulations!"
when "B"
  puts "Well done"
when "C"
  puts "You can do better than that"
when "D"
  puts "Study harder"
when "E"
  puts "Did you do the tests?"
else
  puts "WTF of grade is that"
end
puts "0" if x == 0
x = 0

while x < 10
  puts "Valor de x é: #{x}"
  x += 1
end
x = 0

until x == 10
  puts "Valor de x é: #{x}"
  x += 1
end
for i in [1, 2, 3]
  puts i
end

```ruby
[1,2,3].each do |i|
  puts i
end

RegExp

'abcd' =~ /abcd/
'abcd' =~ /ab[cg][db]/
'abcd' =~ /[a-z]*/
'abcd' =~ /[a-z]*1/
'abcd1' =~ /[a-z]*[0-9]+/
'abcd1' =~ /[a-z]*[0-9]+/
'abcd1' =~ /[a-z]*\d?/
'abcd' =~ /^\w{4}$/
'abcd' =~ /a(.*)d/
'Sorocaba' =~ %r#[Ss]orocaba#

Symbol

:abcd
:aaa_daa
:aaaa_1
"aaa".__id__ == "aaa".__id__
:aaa.__id__ == :aaa.__id__

Range

(1..10)
(1...10)
('a'..'z')
('aa'..'zz')
('a'..'z') === 'q'
('a'..'z').to_a

Methods

def my_method(my_argument)
  puts my_argument
end

my_method("OK")
my_method(1)
my_method "OK"

def my_method(my_first_argument, my_last_optional_argument = false)
  puts "Eu tenho um último argumento" if my_last_optional_argument
  puts my_first_argument
end

Object

"Hi".size
"Sorocaba".reverse
"Sorocaba".downcase
"Sorocaba".upcase
1.zero?
1.even?
32.to_s
-1.abs
/a/.match("aaa")
String.new("aaaa")
String.class

Classes

class Dog
  def bark
    puts "Au"
  end
end

dog = Dog.new
dog.bark
class Dog
  def initialize(age)
    @age = age
  end

  def puppy?
    @age <= 1
  end
end

dog = Dog.new(2)
dog.puppy?

dog2 = Dog.new(1)
dog.puppy?
class Dog
  def self.initialize_puppy
    self.new(0)
  end
end

dog = Dog.initialize_puppy
dog.class
dog.puppy?
class Dog
  def age
    @age
  end

  def age=(age)
    @age = age
  end
end

dog = Dog.initialize_puppy
dog.age
dog.age = 10
dog.age
class Dog
  attr_writer :name
end

dog = Dog.new
dog.name = "Rex"
dog.name
class Dog
  attr_accessor :race
end

dog = Dog.new
dog.race = "Chihuahua"
dog.race
class Dog
  attr_reader :mad?
end

dog = Dog.new
dog.mad?

== and ===

/a/ == 'a'
(1..10) == 1
String == "A"
'a' === 'a'
/a/ === 'a'
(1..10) === 1
String === "A"
case price
when 0..10
  puts "Cheap"
when 11..100
  puts "Not so cheap"
when 101..1000
  puts "Expensive"
when 1001..10000
  puts "Fucking expensive"
else
  puts "I wonder who would buy it"
end
case object
when String
  puts object
when Fixnum
  puts object.to_s
when Symbol
  puts object.to_s
when MyAwesomeClass
  puts object.inspect
end

Array

list_of_chars = ["a", "b", "c"]

list_of_chars[0]
list_of_chars[2]
list_of_chars[-1]

list_of_chars = Array.new(10)

list_of_chars.pop
list_of_chars.push

list_of_chars.unshift
list_of_chars.shift

list_of_chars.size
list_of_chars.join(",")

Hash

hash = { :a => 10, :b => 5 }
hash[:a]
hash[:b]

hash.keys
hash.values

hash2 = { :c => 15, :d => 20}
hash.merge(hash2)

Functional programming

Block

[1,2,3].each do |item|
  puts item
end

Proc and Lambda

my_lambda_method = lambda { |x| puts x }
my_proc_method = Proc.new { |x| puts x }

[1,2,3].each(&my_lambda_method)
[1,3,4].each(&my_proc_method)

def each_squared_element(array, method)
  array.each do |elem|
    method.call(elem)
  end
end

def each_squared_element_2(array, &method)
  array.each do |elem|
    yield(elem)
  end
end

def call_method(method)
  method.call
end

Proc vs Lambda

arg_error_lambda = lambda { |x| puts x }
arg_error_proc = Proc.new { |x| puts x }

call_method(arg_error_lambda)
call_method(arg_error_proc)

returned_lambda = lambda { return "OK" }
returned_proc = Proc.new { return "Not ok" }

call_method(returned_lambda)
call_method(returned_proc)

Modules

module SayHi
  def say_hi
    puts "Hi"
  end
end

class Dog
  include SayHi
end

dog = Dog.new
dog = dog.say_hi

class Dog
  extend SayHi
end

Dog.say_hi

OOP

Array.ancestors
class Dog
  def bark
    puts "Au"
  end
end

class Doberman < Dog
end

dog = Doberman.new
dog.bark

Monkey patches

an_array = ['a', 'b', 'c']

an_array.first
an_array.last

an_array.second

class Array
  def second
    self[1]
  end
end
@fabioyamate
Copy link

  • I'd prefer about iterators than while/until loop
  • case is more interesting syntax than if... we can talk about the === behavior
  • do you need to talk about meta programming? It's interesting, but I think that if you go to a basic java course, you'll not learn about reflection, which is similar...
  • if you are going to tech method_missing, please read this https://github.com/jimweirich/polite_programmer_presentation, talking about this advanced features can lead to bad practices if you do it wrong... your examples are incomplete

@rodrigoflores
Copy link
Author

  • I think it is useful to learn that we could use the same constructs that we have in other languages like C, C++ and Java. I will talk about iterators later.
  • Ok, gonna add case.
  • Metaprogramming is one of the coolest features in Ruby. I won't go deeper teaching it, but at least is a good idea to speak about it and do a quick demo. I may talk how this can lead to bad code and unmaintanable libraries and that we should use respond_to? when using Method missing, but I can't find a way to say how awesome Ruby is without saying about metaprogramming.

@fabioyamate
Copy link

  • but each is more idiomatic that loops, and it is more important, and should be point earlier and used during the course (i can't remember the last time I did a for/while)... this kind of thing is important to note in a course... and not things that you probably will not use...
  • I guess that meta-programming is a topic that the developer should look for it... it is the basic step if he is interesting in learning ruby, you will not aggregate anything for them, and you are not gonna use in any part of the course...

@fabioyamate
Copy link

the case you could explore more, there is some syntax sugar that I like...

case value
when "A", "C"
  do_something
when "B"
  do_another_thing
end

or recently, reading some code:

case
when value > 2 then do_something
when value < 0
  do_another_thing
end

case doesn't need an argument explicitly.. so, in some cases sounds better then if..elsif..end

you could also mention that it do the === so you can mix types in case:

case value
when "a" then do_something
when 1 then do_something_with_integer
end

@fabioyamate
Copy link

about methods, it would be good to say, what obj.method = 1 means... it is just a setter method:

class Foo
  def bar=(value)
    @bar = value
  end
end

and you get the syntax sugar with =.. which sounds much better than Java stters for example...

One thing that I'd like to know is the super, because it behave differently than other languages... you don't pass the arguments to it, you only call it... so if you override a method that receives an argument, you just do:

class Foo < Bar
  def say_bar(value)
    super + " from foo"
  end
end

for me it wasn't clear when using first... I thought that the syntax would be: super(value)...

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