Skip to content

Instantly share code, notes, and snippets.

@appleios
Last active August 29, 2015 14:18
Show Gist options
  • Save appleios/5334b8e7a3f35f531909 to your computer and use it in GitHub Desktop.
Save appleios/5334b8e7a3f35f531909 to your computer and use it in GitHub Desktop.
Ruby weak 1

Please visit new wiki for more info and tasks!

Ruby 1

  • ruby style => OOP everywhere, e.g. 2 + 2 is a call Fixnum(2).+(Fixnum(2))
  • [1,2,3].each {|n| puts n}
  • Simple classes (Fixnum, String, Float)
  • Kernel (puts, gets, p)
  • Simple expressions ("a" + "b", 1 + 5, etc)
  • variables (x = 10)
  • Loops ( 1.upto(5) {|i| puts i}, 5.times do puts "Hey"; end)
  • Cast (1.to_s, 2.to_f, 10.0.to_i)
  • Constants and CamelCase
  • String literals and string interpolation: puts "#{x} + #{y} = #{x+y}"
  • String substitution
puts "foo bar".sub('foo', 'bar')
  • Regular Expressions and scan
"This is a string".scan(/\w/) {|s| puts s}
  • Matching and capturing

Ruby 2

  • Arrays
  • Hashes
  • Code blocks
  • Symbols
  • Methods with blocks, with argument list, hash as last argument
  • Time
  • Extending a Fixnum with cool methods for Time (Time.now + 5.hours)
  • Fixnum -> Bignum

Examples for methods with blocks:

# simple function that puts "Hello" and invoke a block passed to it
def helloBlock(&b)
 puts "Hello"
 yield
end

helloBlock { puts "Yay" }
# => Hello
#    Yay

# lets store a block and invoke it several times
x = lambda {|a,b| puts a+b }

x.call(1,2)
# => 3
x.call("abc","def")
# => abcdef

def sayHelloWithBlock(name, &b)
 5.times do
  yield name
 end
end

sayHelloWithBlock("Mirsaid") {|name| puts "Hello #{name}!" }

# method with *args
def say(*words)
 puts words.join(' ')
end

say "Ruby", "is", "awesome", "!"

# method with hash as last argument
def whatDoYouThinkAbout(hash = {})
 if hash[:pronoun].nil?
  puts "I think that #{hash[:language]} #{hash[:opinion]}.."
 else
  puts "I think that #{hash[:language]} #{hash[:pronoun]} #{hash[:opinion]}.."
 end
end

whatDoYouThinkAbout :language => "PHP", :opinion => "Sucks"
# => I think that PHP - sucks

whatDoYouThinkAbout :language => "C", :pronoun => "is", :opinion => "prolix"
# => I think that C is prolix 

whatDoYouThinkAbout :language => "Ruby", :pronoun => "is", :opinion => "cool"
# => I think that Ruby is cool

x = [1,2,3] + [4,5,6]
x.each { |elem| puts elem.to_s + " is cool!" }

%w{don't you think that ruby is cool?}.each_with_index do |word, index|
 if index == 0
  print "#{word.capitalize} "
 else
  print "#{word} "
 end
end

References and Documentation

Ruby 1

Ruby 2

About Blocks: http://www.reactive.io/tips/2008/12/21/understanding-ruby-blocks-procs-and-lambdas/

CamelCase: https://ru.wikipedia.org/wiki/CamelCase

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