- Herşey bir
Object
(Nesne) - Her
Object
BasicObject
den türemiş. (Objective-C NSObject gibi...) Object.methods
ile o nesneye ait tüm method'larObject.methods.inspect
string olarak method'lar- Mutlaka bir şey geriye döner. Hiçbir şey dönmese
nil
döner.
- 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 daor
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 dafalse
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: '[email protected]',
from: '[email protected]',
subject: 'Important message',
body: source.text)
end
.rb
dosyasının ilk satırı:
# encoding: utf-8
şeklinde olmalı.
puts
un kısaltmasıp
yaniputs "vigo"
ilep "vigo"
aynı...p foo
aslındap foo.inspect
yaparp 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"
a = 5
a.class # Fixnum
a = 9999999999999999999
a.class # Bignum
a = 5.4
a.class # Float
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"
"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"]
%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
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"]]
- Notation for Ruby Literals
- Start using Ruby Percent Notation
- Interpolated olanlara değişken geçilebiliyor. Aynı Çift Tırknak gibi
(Double Quoted Strings) Bunlar:
%Q
,%W
%{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("")
Python
dakidictionary
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}
- 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
Float
da Numeric
in alt class'ıdır.
4.3.class.superclass # Numeric
Array
, Hash
, Symbol
, Enumerator
, Range
hepsinin superclass
'ı
Object
dir...
a = "This is a test"
puts a.methods.join(" ") # tüm methodlar gelir
puts 1000.to_s
puts [1, 2, 3].to_s
- Ç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
@
: instance variable (ya da object variable)@@
: class variableinitialize
: init method'uto_s
: string represantiondef self.method_name
: class method'udef 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]
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
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)
"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"]
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
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 # Global variable
@variable # Instance variable
@@variable # Class variable
variable # Local
variable # Block
CONSTANT # Constant
- { } içine yazılan herşey
yield
a gider...
def call_this_block_twice
yield
yield
end
call_this_block_twice { puts "hello world" } # hello world
# hello world
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...
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]
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">
lambda
create edilincelocal
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ş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
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...
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"
p "hello" if 2==2 if 1==1 # "hello"
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
map
ilecollect
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.
["a", "b", "c"].sample # Ruby 1.9
Random.new.rand(10..20) # Diğer yöntem...
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 = 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
kntrl
+ shift
+ apple
+ e
a = [1, 2, 3, 4] # =>
# uzun
if params[:upcase]
string = string.upcase
end
# kısa, edit in place
string.upcase! if params[:upcase]
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
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
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
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"
]
}
]
gem install unicode_utils
require 'unicode_utils/upcase'
class String
def upcase()
UnicodeUtils.upcase(self, :tr)
end
end
p "uğur".upcase # "UĞUR"
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]
name = "vigo"
def name.model
"#{self} modeli insan"
end
name.methods.include?(:model) # true
name.model # "vigo modeli insan"
class String
def beatbox
"#{self} beatbox"
end
end
name = "vigo" #
name.beatbox # "vigo beatbox"
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
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
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"
puts "Hello \e[31mRED\e[0m"
#!/usr/bin/env ruby
if __FILE__ == $0
# buraya...
end
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 }
- Ruby 1.9+'da
Hash
deki sıra bozulmuyor. 1.8'de aynı python'daki gibi sıra mıra yok...
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.