Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Ruby Tips

Ruby Tips

Genel

  • Herşey bir Object (Nesne)
  • Her Object BasicObjectden türemiş. (Objective-C NSObject gibi...)
  • Object.methods ile o nesneye ait tüm method'lar
  • Object.methods.inspect string olarak method'lar
  • Mutlaka bir şey geriye döner. Hiçbir şey dönmese nil döner.

Style Guide

  • Github tarafından hazırlanan Style Guide
  • Değişkenler küçük harfle ve anlaşılır şekilde snake_cased
  • Class isimleri CameCase
  • Constant isimleri SCREAMING_SNAKE_CASE
  • Fonksiyonlar (def) arasında 1 boş satır, method'lar arasında mantıksal ayrımlar:
  • Eğer mulitline değilse (if/unless) then kullanma!
  • Asla and ya da or kullanma. Yerine && veya || kullan!
  • Tek satırlık işler için do..end kulllanma {} kullan!
  • Method'a default parametre verirken eşittir (=) etrafına space
  • Değişken init ederken || kullan, eğer nil ya da false ise set et ama boolean için kullanma!
def some_method(arg1 = :default, arg2 = nil, arg3 = [])
  # do something...
end

name || = 'Hello'  # default

def send_mail(source)
  Mailer.deliver(to: 'bob@example.com',
                 from: 'us@example.com',
                 subject: 'Important message',
                 body: source.text)
end

.rb dosyasının ilk satırı:

# encoding: utf-8

şeklinde olmalı.

Printing: print, puts, p

  • putsun kısaltması p yani puts "vigo" ile p "vigo" aynı...
  • p foo aslında p foo.inspect yapar p foo.to_s yapmaz!
  • puts satır sonuna "\n" ekler, print eklemez.
name = "vigo"
puts "hello my name is #{name}"              # hello my name is vigo

puts "1 + 2 = #{1 + 2}"                      # 1 + 2 = 3
puts '1 + 2 = #{1 + 2}'                      # 1 + 2 = #{1 + 2}
                                             # Tek tırnak ile Çift tırnak farklı...

b = 1_000                                    # 1000
b = 5_333_1                                  # 53331

a, b = 1, 2

@x = "vigo"                                  # "vigo"
x = "lego"                                   # "lego"
"x is: #{x}"                                 # "x is lego"
"x is: #@x"                                  # "x is vigo" # curly kullanmadan
"x is: #{@x}"                                # "x is: vigo"
$x = "crap"                                  # "crap"
"#{$x} is ok"                                # "crap is ok"
"#$x is ok"                                  # "crap is ok"

Data Types

Numbers

a = 5
a.class                                      # Fixnum

a = 9999999999999999999
a.class                                      # Bignum

a = 5.4
a.class                                      # Float

Strings

Methods

name = "vigo"
name.class                                   # String
name.upcase                                  # VIGO
name.upcase.downcase                         # vigo
name.rjust(10)                               # "      vigo"
name.rjust(10, ".")                          # "......vigo"

puts ?A.ord                                  # ordinal değeri 65
"A".ord                                      # 65

 # find / replace
p "hello world".sub("world", "vigo")         # hello vigo, sadece ilki yakalar
p "hello world".sub("o", "a")                # hella world
p "hello world".gsub("o", "a")               # hella warld, hepsini yakalar

t = "Hello World"
t["hello"]                                   # nil
t["Hello"]                                   # Hello
t["Hello"].nil?                              # false
t["vigo"].nil?                               # true

"abc".concat("hd")                           # "abchd"
"hello" "world"                              # "helloworld"
x = "abc" "def"                              # "abcdef"

Basic Regex

"Hello world".sub(/^He/,"Ke")              # "Kello world" regex'le beraber!
"i have 3 eggs".scan(/\d+ eggs/)           # ["3 eggs"]
"i have 3 eggs".scan(/(\d+) eggs/)         # [["3"]]
"i have 3 eggs".scan(/(\d+) eggs/).first   # ["3"]

"This is a test".scan(/\w+/)               # ["This", "is", "a", "test"]

Format String, Interpolation, printf, Concat

%c  character
%d  decimal (integer) number (base 10)
%e  exponential floating-point number
%f  floating-point number
%i  integer (base 10)
%o  octal number (base 8)
%s  a string of characters
%u  unsigned decimal (integer) number
%x  number in hexadecimal (base 16)
%%  print a percent sign
\%  print a percent sign
printf("üç basamaklı 5 = %03d\n", 5)         # üç basamaklı 5 = 005
sprintf("üç basamaklı 5 = %03d\n", 5)        # => "üç basamaklı 5 = 005\n"
sprintf("2 basamak: %.2f", 4.12345)          # => "4.12"
sprintf("3 basamak: %.3f", 4.12345)          # => "4.123"

"Hello %s" % "World"                         # => "Hello World"
"Hello %s %d" % ["World", 5]                 # => "Hello World 5"

filename = "%s/%s.%04d.txt" % ["dirname", "filename", 23]
                                             # => "dirname/filename.0023.txt"

out = ''
out << "hello "
out << "world"                               # "hello world"
p out

Symbols

Arrays

Array sıfır index'li...

my_array = Array.new                         # []
my_array = []                                # [] aynısı

my_array = [1, 3, 4]
my_array[0]                                  # 1

["vigo", ["lego", ["hugo"]], 5].flatten      # ["vigo", "lego", "hugo", 5]
["ali", "veli", "vonke"].member?("ali")      # true
[1, 2, 3, 4, 5, 0].drop(3)                   # [4, 5, 0]

a = [1, 2, 3, 4, 5]
a[4..5]                                      # => [5]
a[1..3]                                      # => [2, 3, 4] yani 0 indeksli 
                                             # 1.elemandan itibaren 3 tane al

[1, 4, 5].max                                # => 5

a = [1, 2, 3, 4, 5]                          # [1, 2, 3, 4, 5]
a.first                                      # => 1
a.first(1)                                   # => 1
a.first(2)                                   # => [1, 2]
a.last                                       # => 5
a.last(2)                                    # => [4, 5]


names = %w{fred jess john}                   # ["fred", "jess", "john"]
ages = [38, 47, 91]                          # [38, 47, 91]
names.zip(ages)                              # [["fred", 38], ["jess", 47], ["john", 91]]
Hash[names.zip(ages)]                        # {"fred"=>38, "jess"=>47, "john"=>91}
locations = %w{spain france usa}             # ["spain", "france", "usa"]
names.zip(ages, locations)                   # [["fred", 38, "spain"], ["jess", 47, "france"], ["john", 91, "usa"]]

Ruby Literals: %, %w, %Q, %q, %x, %r

%{Merhaba Dünya}                             # "Merhaba Dünya"
%|hello|                                     # "hello"

% hello .length                              # => 5

%w{a b c d}                                  # ["a", "b", "c", "d"]
%w{a b c d}.class                            # Array

%x[find . -name '*.txt' | sort]              # Execute shell command
%x[find . -name '*.txt' | sort].split("\n")  # ["./api-tips.txt", "./bind-tips.txt"]

x = %q{hello
this is
multi line
}
                                             # => "hello\nthis is\nmulti line\n"
puts %{Merhaba dünya "nasılsın?"}            # Merhaba dünya "nasılsın?"

num = 2
%q{1+1=#{num}}                               # "1+1=\#{num}" single quote gibi...
%Q{1+1=#{num}}                               # "1+1=2" double quote gibi...
%w{hello world #{num}}                       # ["hello", "world", "\#{num}"]
%W{hello world #{num}}                       # ["hello", "world", "2"]

input = "hello"
%r((.*)#{input})i                            # => /(.*)hello/i

x = "this"                                   # "this"
x = %{hello}                                 # "hello"
x = %|hello|                                 # "hello"
% hello .length                              # 5

binary_letters = %w(01100100 01101111 01100111 00011111 01110101 01101101 00100000 01100111 11111100 01101110 11111100 01101110 00100000 01101011 01110101 01110100 01101100 01110101 00100000 01101111 01101100 01110011 01110101 01101110 00100000 00111101 00101001)
binary_letters.map!{ |letter|
  letter.to_i(2).chr
}
binary_letters.join("")

Hashes

  • Pythondaki dictionary
  • key => value
  • Herşey bir key olabilir. (String, Array, Symbol)
my_hash = Hash.new                           # {}
my_hash = {}                                 # {} aynısı
my_hash['user'] = "vigo"                     # {"user" => "vigo"}
                                         
my_hash = { "user" => "vigo"}                # {"user" => "vigo"}
                                         
person = { :name => "vigo", :age => 35 }     # {:name=>"vigo", :age=>35}
person[:name]                                # "vigo"

h = {"veli" => 20, "ali" => 10}              # sort has by value
p h
sorted = h.sort_by do |key, value|
value
end
p Hash[*sorted.flatten]                      # {"ali"=>10, "veli"=>20}

h = Hash.new("Go Fish")
p h                                          # {}

h["a"] = 100
h["b"] = 200
p h                                          # {"a"=>100, "b"=>200}

p h["c"]                                     # "Go Fish"
p h["boooooooooooooooooooo"]                 # "Go Fish"

p h.keys                                     # ["a", "b"]


h = Hash.new do |hash, key|
  hash[key] = "Go Fish: #{key}"
end
p h                                          # {}
p h["c"]                                     # "Go Fish: c"


a = Hash.new do |hash, k1|
  Hash.new do |hash, k2|
    hash[k1] = k2
  end
end
p a[1][2]                                    # 2

h = {a: 1, b: 2}
p h                                          # {:a=>1, :b=>2}
h.size                                       # 2

d = {:a=> 5, :b=> 1}                         # {:a=>5, :b=>1}
d.delete(:a)                                 # => 5
d                                            # {:b=>1}

Objects

  • Her objenin to_s method'u var...
"hello".class                                # String
:hello.class                                 # Symbol
51.class                                     # Fixnum
0xff.class                                   # Fixnum => 255
0b11.class                                   # Fixnum => 3   => 0b=Binary, 11 => 3
0b1111                                       # Fixnum => 15
3.14.class                                   # Float
9999999999999999999.class                    # Bignum
[].class                                     # Array
{}.class                                     # Hash
5.times.class                                # Enumerator
("a".."l").class                             # Range

String.ancestors                             # => [String, Comparable, Object, PP::ObjectMixin, Kernel, BasicObject]
Fixnum.ancestors                             # => [Fixnum, Integer, Numeric, Comparable, Object, PP::ObjectMixin, Kernel, BasicObject]

person = { :name => "vigo", :age => 35 }
person.class                                 # Hash
person.inspect                               # "{:name=>\"vigo\", :age=>35}"

Fixnum ve Bignum, Integerın alt class'ıdır.

5.class.superclass                           # Integer
9999999999999999999.class.superclass         # Integer

Floatda Numericin alt class'ıdır.

4.3.class.superclass                         # Numeric

Array, Hash, Symbol, Enumerator, Range hepsinin superclassObjectdir...

a = "This is a test"
puts a.methods.join(" ")                     # tüm methodlar gelir

puts 1000.to_s
puts [1, 2, 3].to_s

Function (Fonksiyon, def)

  • Çağırılırken parantez kullanmak zorunlu değil!
  • return yazmak zorunlu değil!
def my_function
end

def my_method
  p __method__
  p __callee__
end

my_method

def my_calc(a, b)
  a + b
end

my_calc 8,9        # 17
my_calc(8,9)       # 17

Class

  • @: instance variable (ya da object variable)
  • @@: class variable
  • initialize: init method'u
  • to_s: string represantion
  • def self.method_name: class method'u
  • def method_name: instance method'u

Basit bir class örneği:

class Person
  attr_reader :first_name, :last_name

  def initialize(first_name, last_name)
    @first_name = first_name
    @last_name = last_name
  end
end

p = Person.new("vigo", "bronx") # #<Person:0x007f973b948750 @first_name="vigo", @last_name="bronx">


class Person
  attr_reader :first_name, :last_name

  def initialize(first_name, last_name)
    @first_name = first_name
    @last_name = last_name
  end

  def to_s # buraya dikkat
    "#@first_name #@last_name"
  end
end

p = Person.new("vigo", "bronx") # vigo bronx


class MegaGreeter
    attr_accessor :names
    def initialize(names = "World")                              # Create the object
        @names = names
    end
    def say_hi                                                   # Say hi to everybody
        if @names.nil?
            puts "..."
        elsif @names.respond_to?("each")
            @names.each do |name|                                # @names is a list of some kind, iterate!
                puts "Hello #{name}!"
            end
        else
            puts "Hello #{@names}!"
        end
    end
    def say_bye                                                  # Say bye to everybody
        if @names.nil?
            puts "..."
        elsif @names.respond_to?("join")
            puts "Goodbye #{@names.join(", ")}. Come back soon!" # Join the list elements with commas
        else
            puts "Goodbye #{@names}. Come back soon!"
        end
    end
end

mg = MegaGreeter.new                                             # #<MegaGreeter:0x007ff39a0ccc00 @names="World">
mg.say_hi                                                        # Hello World!
mg.say_bye                                                       # ...
mg.names = "Zeke"                                                # "Zeke"
mg.say_hi                                                        # Hello Zeke!
mg.say_bye                                                       # Goodbye Zeke. Come back soon!

mg.names = ["vigo", "turbo", "max"]
mg.say_hi                                                        # Hello vigo!
                                                                 # Hello turbo!
                                                                 # Hello max!
mg.say_bye                                                       # Goodbye vigo, turbo, max. Come back soon!

attr_accessor: getter ve setter fonksiyonlarını otomatize ediyor. Bu sayede, :names için setnames ve getnames gibi fonkisyonları yazmaya gerek kalmıyor.

class Person
  attr_accessor :name, :age
  def initialize(data)
    @name, @age = data.values_at(:name, :age)
  end
end
vigo = Person.new(name: "Vigo", age: 39)
puts "#{vigo.name} #{vigo.age}"

Class ve Instance method örneği:

class Square
  def self.test_method              # class method
    puts "Hello from Square class"
  end
  def test_method                   # instance method
    puts "Hello from instance"
  end
end
Square.test_method     #=> "Hello from Square class" self.test_method
Square.new.test_method #=> "Hello from instance" test_method

Classe Square
  def Square.test_method
    puts "Hello from Square class"
  end
end
class Person
  attr_accessor :name, :age
end
p = Person.new
p.instance_variables         # [@age, @name]

Overriding Method, Encapsulation, Polymorphism

x = "Test"
x.class                                      # String
x.length                                     # 4
x.upcase                                     # "TEST"

class String
  def length
    20
  end
end

x.length                                     # 20 kafamıza göre length'i yedik!

Encapsulation

class Person
  def initialize(name)
    set_name(name)
  end
  def name
    @first_name + ' ' + @last_name
  end
  def set_name(name)
    first_name, last_name = name.split(/\s+/)
    set_first_name(first_name)
    set_last_name(last_name)
  end
  def set_first_name(name)
    @first_name = name
  end
  def set_last_name(name)
    @last_name = name
  end
end
p = Person.new("Vigo Kadriyani")
p.name                           # Vigo Kadriyani
p.set_last_name("Koon")
p.name                           # Vigo Koon



class Person                     # private
  def initialize(name)
    set_name(name)
  end
  def name
    @first_name + ' ' + @last_name
  end
  private
  def set_name(name)
    first_name, last_name = name.split(/\s+/)
    set_first_name(first_name)
    set_last_name(last_name)
  end
  def set_first_name(name)
    @first_name = name
  end
  def set_last_name(name)
    @last_name = name
  end
end
p = Person.new("Vigo Kadriyani")
p.set_last_name("joooooooooooooooo") # NoMethodError: private method `set_last_name' called for #<Person:0x007f8d094b3e60>
p.private_methods.join(' ')



class Person                      # private and public
  def initialize(name)
    set_name(name)
  end
  def name
    @first_name + ' ' + @last_name
  end
  private
  def set_name(name)
    first_name, last_name = name.split(/\s+/)
    set_first_name(first_name)
    set_last_name(last_name)
  end
  public
  def set_first_name(name)
    @first_name = name
  end
  def set_last_name(name)
    @last_name = name
  end
end
p = Person.new("Vigo Kadriyani")
p.public_methods.join(' ')



class Person                        # protected
  def initialize(age)
    @age = age
  end
  def age
    @age
  end
  def age_difference_with(other_person)
    (self.age - other_person.age).abs
  end
  protected :age
end
vigo = Person.new(40)
ceci = Person.new(36)
puts vigo.age_difference_with(ceci) # 4
puts ceci.age                       # NoMethodError: protected method `age' called for #<Person:0x007f9f21533410 @age=36>
puts ceci.protected_methods         # [:age]

Polymorphism

class Animal
    attr_accessor :name
    def initialize(name)
      @name = name
    end
end
class Cat < Animal
    def talk
      "Miyav"
    end
end
class Dog < Animal
  def talk
    "Hav Hav"
  end
end
animals = [Cat.new('Biduk'), Dog.new('Karabas'), Dog.new('Chuck')]
animals.each do |animal|
  puts animal.talk
end
                                    # Miyav
                                    # Hav Hav
                                    # Hav Hav

Inheritance

class Animal
end

class Duck < Animal
  def speak
    puts 'Quack! Quack'
  end
end

class Dog < Animal
  def speak
    puts 'Bau! Bau!'
  end
end

a = Duck.new
b = Dog.new
a.speak       # Quack! Quack
b.speak       # Bau! Bau!
class Person
  def initialize(name)
    @name = name
  end
  def name
    @name
  end
end

class Doctor < Person
  def name
    "Dr " + super
  end
end

Beginning Ruby, Chapter 6: Classes, Objects and Modules

class Shape
end

class Square < Shape
  def initialize(side_length)
    @side_length = side_length
  end
end

class Triangle < Shape
  def initialize(base_width, height, side1, side2, side3)
    @base_width = base_width
    @height = height
    @side1 = side1
    @side2 = side2
    @side3 = side3
  end
end

S = Square.new(5)
T = Triangle.new(10,20,5,6,7)

Type Conversions

"5".to_i                                     # => 5                        String => Integer
"5".to_f                                     # => 5.0                      String => Float
"vigo".to_sym                                # => :vigo                    String => Symbol
5.5.to_int                                   # => 5                        Float => Integer
("a".."d").to_a                              # => ["a", "b", "c", "d"]     Range => Array
[1, 2, 3, 4].to_s                            # => "[1, 2, 3, 4]"           Array => String
7.to_s(2)                                    # => "111"                    Integer => Binary
"111".to_i(2)                                # => 7                        Binary => Integer
"A".ord

["1110110", "1101001", "1100111", "1101111"].map do |l|
  l.to_i(2).chr
end.join("")                                 # => "vigo"

["v","i","g","o"].map do |c|
  c.ord.to_s(2)
end
                                             # => ["1110110", "1101001", "1100111", "1101111"]

Nested Classes

class Drawing
  class Line
  end
  class Circle
  end
end

class Drawing
  def Drawing.give_me_a_circle
    Circle.new
  end
  class Line
  end
  class Circle
    def what_am_i
      "This is a circle"
    end
  end
end
a = Drawing.give_me_a_circle
a.what_am_i                                  # This is a circle

b = Drawing::Circle.new
b.what_am_i                                  # This is a circle

Scope of Constants

def circumference_of_circle(radius)
  2 * Pi * radius
end
Pi = 3.141592
puts circumference_of_circle(10)             # 62.83184

class OtherPlanet
  Pi = 4.5
  def OtherPlanet.circumference_of_circle(radius)
    radius * 2 * Pi
  end
end
puts OtherPlanet::Pi                         # 4.5
puts OtherPlanet.circumference_of_circle(10) # 90

Variable Scope

$variable                                    # Global variable
@variable                                    # Instance variable
@@variable                                   # Class variable
variable                                     # Local
variable                                     # Block
CONSTANT                                     # Constant

yield, lambda, Proc, Block, Closure

yield

  • { } içine yazılan herşey yielda gider...
def call_this_block_twice
  yield
  yield
end

call_this_block_twice { puts "hello world" } # hello world
                                             # hello world

Proc

my_proc = Proc.new { puts "Hello" }
my_proc.call                                 # Hello

my_proc = Proc.new do                        # Aynı şey...
  puts "Hello"
end
my_proc.call                                 # run...

my_proc = lamda { puts "Hello" }             # bu da lamda şeklinde...
my_proc.call                                 # run...

my_proc = -> { puts "Hello" }                # ruby 1.9+: stabbing lambdas
my_proc.call                                 # run...

lambda

items = ["Bu bir", "bu iki", "bu üç"]        # bu standart bişi
items.each do |item|                         # bunu lambda yapalım
  puts item
end

printer = lambda { |item| puts item }
items.each(&printer)                         # proc'u block'a çevir...


items.each(&lambda{ |t| puts t})             # ya da tek satır lambda

def each(&block)                             # block'u proc'a çevir...

class B
  def double(x)
    x * 2
  end
end
b = B.new
[1, 2, 3].map(&b.method(:double))            # [2, 4, 6]

Block

class Tweet
  attr_accessor :status
  def initialize
    yield self if block_given?
  end
end

Tweet.new do |t|
  t.status = "Hello"
end                                          # #<Tweet:0x007f8c2d1a11c8 @status="Hello">

Closure

  • lambda create edilince local değişken korunuyor...
def tweet_as(user)
  lambda { |tweet| puts "#{user}: #{tweet}" }
end

vigo_tweet = tweet("vigo")                   # lambda { |tweet| puts "vigo: #{tweet}" } oldu...
vigo_tweet.call("Hello World")               # lambda { |tweet| puts "vigo: Hello World" } oldu...

Eşitlik

Regex Eşitliği (=~)

Eşitliği verilen Regex patternine göre yapar...

a = "hello 2012"
print "metin içinde 20 ile başlayan 4 basamaklı sayı var" if a =~ /20\d{2}+/

example = "\nhello\n\t\n\n\n \nworld"
example.each_line{ |line| print line unless line =~ /^\s*\n/ }
                                             # hello
                                             # world

<=> Spaceship

x <=> y                                      # eğer x = y ise 0 döner
                                             # eğer x > y ise 1,
                                             # eğer y > x ise -1
                                             # 1 , 0 , -1 gibi bir sıra...

Koşullar: if, else, unless ve ternary

unless: If not anlamında...

enabled = true if enabled.nil?               # enabled eğer nil'se...
p enabled                                    # true

p 1 > 2 ? "true" : "false"                   # "false"

a = 5
"büyük" if not a < 1                         # => "büyük"
"büyük" unless a < 1                         # => "büyük"
                                             # yani a, 1'den küçük değilse...
"Not Empty" unless "Hello".strip.empty?      # "Not Empty"

Chained If (Zincirleme If)

p "hello" if 2==2 if 1==1                    # "hello"

Koşullar: case, when

score = 70
result = case score
     when 0..40: "Fail"
     when 41..60: "Pass"
     when 61..70: "Pass with Merit"
     when 71..100: "Pass with Distinction"
     else "Invalid Score"
end
puts result                                  # Pass with Merit

Enumaration, Iteration: each, upto, downto, times, step, range, map, select, until

  • map ile collect aynı şey...
numbers = [1, 122, 323, 23]
                                             # [1, 122, 323, 23]
numbers.each { |number| puts number }
                                             # 1
                                             # 122
                                             # 323
                                             # 23
                                             # => [1, 122, 323, 23]

5.upto(10) { |i| puts i }
                                             # 5
                                             # 6
                                             # 7
                                             # 8
                                             # 9
                                             # 10
                                             # => 5

10.upto(20) do |i|
  next if i.even?
  puts i
end
                                             # 11
                                             # 13
                                             # 15
                                             # 17
                                             # 19
                                             # => 10

5.downto(3) { |i| puts i }
                                             # 5
                                             # 4
                                             # 3
                                             # => 5

5.times do puts "vigo" end
                                             # vigo
                                             # vigo
                                             # vigo
                                             # vigo
                                             # vigo
                                             # => 5

5.times do |number|
  puts "vigo #{number}"
end
                                             # vigo 0
                                             # vigo 1
                                             # vigo 2
                                             # vigo 3
                                             # vigo 4
                                             # => 5

0.step(10) do |num|
  p num
end
                                             # 0
                                             # 1
                                             # :
                                             # :
                                             # 10
                                             # => 0
                                             # 0'dan, 0 dahil, 10'a kadar
                                             # 10 dahil...

0.step(10, 2) do |num|
  p num
end
                                             # 0
                                             # 2
                                             # 4
                                             # 6
                                             # 8
                                             # 10
                                             # => 0
                                             # 0'dan, 0 dahil, 10'a kadar
                                             # 2'şer 2'şer, 10 dahil...

(1..10).each { |i| puts "line #{i}" }
                                             # 1
                                             # 2
                                             # :
                                             # 10
                                             # => 1..10
                                             # 1'den 10'a kadar 10 dahil
                                             # Range


(1...10).each { |i| puts "line #{i}" }
                                             # 1
                                             # 2
                                             # :
                                             # 9
                                             # => 1...10
                                             # 1'den 10'a kadar, 10 dahil değil
                                             # Range

[10..20]                                     # => [10..20]
[*10..20]                                    # => [10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
Array(10..20)                                # => [10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]

("a".."e").each do |char|
  p char
end
                                             # "a"
                                             # "b"
                                             # "c"
                                             # "d"
                                             # "e"
                                             # => "a".."e"

['apple','cherry','apple','banana'].map do |fruit|
  fruit.reverse
end.sort
                                             # => ["ananab", "elppa", "elppa", "yrrehc"]

food = ['apple','cherry','apple','banana'].map do |fruit|
  fruit.reverse
end.select do |fruit|
  fruit.match(/^a/)
end
p food                                       # ["ananab"]

fruits = ['apple','cherry','apple','banana']
fruits.any? do |f|
  p f if f.length > 5
end
                                             # "cherry"

filtered = ["Bozhidar", "Steve", "Sarah"].select do |name|
  name.start_with?("S")
end.map do |name|
  name.upcase
end
                                             # ["STEVE", "SARAH"]

a = [1, 2, 3, 4].map do |bar|
  bar * 2
end
                                             # => [2, 4, 6, 8]
a                                            # [2, 4, 6, 8]

a = [1, 2, 22, 4, 8, 220]
a.drop_while { |i| i < 5 }.sort              # [4, 8, 22, 220]

i = 1
until i > 50
  print i
  i += 1
end                                          # 1'den 50'ye kadar (50 dahil...)

ri Array#drop_while

Drops elements up to, but not including, the first element for which the block returns nil or false and returns an array containing the remaining elements.

Matematiksel

random

["a", "b", "c"].sample                       # Ruby 1.9
Random.new.rand(10..20)                      # Diğer yöntem...

stdin, input, get

print "Enter your grade: "
grade = gets.chomp
case grade
when "A"
  puts 'Well done!'
when "B"
  puts 'Try harder!'
when "C"
  puts 'You need help!!!'
else
  puts "You just making it up!"
end

File System, IO

file = File.new('test.txt', 'w')             # 'w' Write Mode
file.write("Hello")
file.close

file = File.open('test.txt', 'r')            # 'r' Read Mode
p file.readlines                             # => ["Hello"]
file.close

Tricks

TextMate: Execute Update Markers

kntrl + shift + apple + e

a = [1, 2, 3, 4] # =>

Edit in Place, !

  # uzun
  if params[:upcase]
    string = string.upcase
  end

  # kısa, edit in place
  string.upcase! if params[:upcase]

Interaktif Konsol

irb

pry

gem install pry pry-doc

ri Array.drop_while      # Array.drop_while hakkında yardım
ri String.upcase

ri String#upcase

help
ITEM -h                  # komut hakkında help

install-command gist     # gist için ilave gem lazım oldu kurdu.
gist -h

.ls                      # .SHELL_KOMUTU
.cd
.pwd

show-doc [].include?
show-doc "".each_line
show-doc String#each_line

show-method "".each_line
show-method "".each_line -l # shows with line numbers

require 'ruby-duration'     # modülün içine gir
ls Duration
help ls

cd Duration
ls
show-method format

cd Regexp
nesting
jump to 1

show-input # yanlış line # 2 olsun
amend-line 2 CORRECT_CODE

Standart Kütüphane Fonksiyon'ları / Class'ları

Date

require 'Date'
t = Date.new(2011, 12, 24)                   # #<Date: 2011-12-24 ((2455920j,0s,0n),+0s,2299161j)>
t.strftime('%d %B %Y %A').upcase             # "24 DECEMBER 2011 SATURDAY"

Date::DAYNAMES.each do |day_name|
  puts "today is #{day_name}"
end
                                             # today is Sunday
                                             # today is Monday
                                             # today is Tuesday
                                             # today is Wednesday
                                             # today is Thursday
                                             # today is Friday
                                             # today is Saturday

open-uri

http://ugur.ozyilmazel.com sitesini indir ve satır satır oku:

require 'open-uri'
www = open('http://ugur.ozyilmazel.com')
html = www.read.split("\n")
html.each_with_index do |line, index|
  html[index] = line.strip
end
p html

json

require 'json'
require 'open-uri'
p JSON.load open('https://github.com/vigo.json').read

h = [{:name=>"vigo", :age=>20, :children=>["a","b"]}]
jj h

[
  {
    "name": "vigo",
    "age": 20,
    "children": [
      "a",
      "b"
    ]
  }
]

Faydalı gemler

unicode_utils

gem install unicode_utils
require 'unicode_utils/upcase'
class String
  def upcase()
    UnicodeUtils.upcase(self, :tr)
  end
end
p "uğur".upcase                              # "UĞUR"

nokogiri

gem install nokogiri
require 'nokogiri'
require 'open-uri'

www = open("http://ugur.ozyilmazel.com")
html = Nokogiri::HTML(www)

p "css..."
html.css('ul.main-navigation li').each do |match|
  p match.content
end
p ""

p "xpath..."
html.xpath('//h1/a').each do |match|
  p match.content
end
p ""

p "search..."
html.search('h1.entry-title', '//footer/a').each do |match|
  p match.content
end
p ""

awesome_print www

gem install awesome_print
require 'awesome_print'
ap [1,2,3]

Monkey Patching

String custom method -very dirty-

name = "vigo"
def name.model
    "#{self} modeli insan"
end

name.methods.include?(:model)                # true
name.model                                   # "vigo modeli insan"

String custom method

class String
    def beatbox
        "#{self} beatbox"
    end
end

name = "vigo"                                #
name.beatbox                                 # "vigo beatbox"

FancyDate: Hash, Object ile Custom Komut

require 'Date'
FancyDate = Hash.new do |hash, month|
  Hash.new do |hash, day|
    Hash.new do |hash, year|
      Date.new(year, month, day)
    end
  end
end
Date::ABBR_MONTHNAMES[1..-1].each_with_index do |name,index|
  Object.const_set(name, FancyDate[index+1])
end

p Feb[28][2010]                              # 2010-02-28

Date

require 'Date'
date = Date.today                            # => #<Date: 2012-11-03 ((2456235j,0s,0n),+0s,2299161j)>

class Date
  def inspect
    "#{ self.day }.#{ self.month }.#{ self.year }"
  end
end

date                                         # => 3.11.2012 Turkish

Türkçe DateTime

require 'Date'
MONTHNAMES_TR = [nil,
  "Ocak", "Şubat", "Mart", "Nisan", "Mayıs", "Haziran",
  "Temmuz", "Ağustos", "Eylül", "Ekim", "Kasım", "Aralık"
]
ABBR_MONTHNAMES_TR = [nil,
  "Oca", "Şub", "Mar", "Nis", "May", "Haz",
  "Tem", "Ağu", "Eyl", "Eki", "Kas", "Ara"
]
DAYNAMES_TR = [
  "Pazar", "Pazartesi", "Salı", "Çarşamba",
  "Perşembe", "Cuma", "Cumartesi"
]
ABBR_DAYNAMES_TR = [
  "Paz", "Pzt", "Sal", "Çar",
  "Prş", "Cum", "Cts"
]

class DateTime
  def strftime_tr(format)
    format.gsub!(/%a/, ABBR_DAYNAMES_TR[self.wday])
    format.gsub!(/%A/, DAYNAMES_TR[self.wday])
    format.gsub!(/%b/, ABBR_MONTHNAMES_TR[self.mon])
    format.gsub!(/%B/, MONTHNAMES_TR[self.mon])
    self.strftime(format)
  end
end

t = DateTime.now                         # #<DateTime: 2012-11-21T21:05:00+02:00 ((2456253j,68700s,168110000n),+7200s,2299161j)>
t.strftime_tr("%d %B %Y %A saat %H:%M")  # "21 Kasım 2012 Çarşamba saat 21:05"

strftime komple override ederek:

require 'Date'

MONTHNAMES_TR = [nil,
  "Ocak", "Şubat", "Mart", "Nisan", "Mayıs", "Haziran",
  "Temmuz", "Ağustos", "Eylül", "Ekim", "Kasım", "Aralık"
]
ABBR_MONTHNAMES_TR = [nil,
  "Oca", "Şub", "Mar", "Nis", "May", "Haz",
  "Tem", "Ağu", "Eyl", "Eki", "Kas", "Ara"
]
DAYNAMES_TR = [
  "Pazar", "Pazartesi", "Salı", "Çarşamba",
  "Perşembe", "Cuma", "Cumartesi"
]
ABBR_DAYNAMES_TR = [
  "Paz", "Pzt", "Sal", "Çar",
  "Prş", "Cum", "Cts"
]

class Date
  alias :strftime_nolocale :strftime
  def strftime(format)
    format = format.dup
    format.gsub!(/%a/, ABBR_DAYNAMES_TR[self.wday])
    format.gsub!(/%A/, DAYNAMES_TR[self.wday])
    format.gsub!(/%b/, ABBR_MONTHNAMES_TR[self.mon])
    format.gsub!(/%B/, MONTHNAMES_TR[self.mon])
    self.strftime_nolocale(format)
  end
end

d = Date.new(2012,1,1)                    # #<Date: 2012-01-01 ((2455928j,0s,0n),+0s,2299161j)>
d.strftime("%d %B %Y %A")                 # "01 Ocak 2012 Pazar"

Command Line / Shell Scripting

Renkli print

puts "Hello \e[31mRED\e[0m"

Dosya'dan execute

 #!/usr/bin/env ruby
 if __FILE__ == $0
   # buraya...
 end

Oneline

ruby -e 'p ENV'                      # Environment'i göster
ruby -c file.rb                      # ruby syntax'ı kontrol et

Shell Command çalıştırmak www

exec 'echo "hello $HOSTNAME"'
system 'echo "hello $HOSTNAME"'
puts $? # returns exit code
today = `date`
p today
IO.popen("date") { |f| puts f.gets }

Diğer Hatırlatmalar

  • Ruby 1.9+'da Hashdeki sıra bozulmuyor. 1.8'de aynı python'daki gibi sıra mıra yok...

@fatiherikli

This comment has been minimized.

Copy link

commented Dec 13, 2012

harika bir kaynak olmus :)

python 2.7 ve sonraki surumlerde collections altinda python ile implement edilmis OrderedDict adinda bir type var.

http://docs.python.org/2/library/collections.html#collections.OrderedDict

@ghost

This comment has been minimized.

Copy link

commented Dec 15, 2012

Efsane efsane :)

@vigo

This comment has been minimized.

Copy link
Owner Author

commented Dec 15, 2012

sağol fatih. henüz bitmiş değil. zaten bitmek diye bir kavram yok. yeni öğrendiğim her şeyi ekliyorum. bunun python'u bash'i applescript'i filan da var. hepsini zaman içinde gist olarak paylaşıcam.

@dara

This comment has been minimized.

Copy link

commented Jan 16, 2013

Bu temiz bir derleme olmuş. Mesela $var şeklinde değişkeni isimlendirince # + curly kullanmadan da (sadece) # ile ekrana basilabildigini bilmiyordum.

@vigo

This comment has been minimized.

Copy link
Owner Author

commented Mar 22, 2013

teşekkürler arkadaşlar.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.