Ruby 1.9 w pigułce

[In a Nutshell]

[phil•ip hall•strom]

Na Sigmie jest zainstalowany ruby 1.8.7 (2009-06-08 patchlevel 173). Uwaga: wersje z mniejszym patchlevel mają problemy z security i/lub wyciekami pamięci.

Aktualna wersja: ruby 1.9.2-p180.

Repozytorium SVN z kodem jest na ruby-lang.org. Ostatnia wrzutka ma numer: 25370.

Wszystkie dane z dnia 20.06.2011.

[Edsger W. Dijkstra]

Elegance is not a dispensable luxury but a quality that decides between success and failure.

Hasze

h = {1 => 2,3 => 4,5 => 6}
h.keys
h.values
h[7] = 8
h #  {5=>6, 1=>2, 7=>8, 3=>4}
h.to_a

Tablice

a = [1,2,3,4,5,6]
a.object_id
a.to_a.object_id
str = "hello\nworld"
str.to_a
4.to_a # warning: default 'to_a' will be obsolete
*c = 1, 2, 3, 4

Symbole

Object.new.methods.sort # 1.9 lista symboli, 1.8 – napisów
Object.new.methods.grep(/methods/)
words= %w{ witaj świecie }
words.map { |w| w.upcase }
words.map(&:upcase)  # 1.9

Enumerators 1.8

a = [2,4,6,8]
a.each {|n| p n + 10}
a.each_with_index {|n,i| p "#{i} -> #{n}" }
a.map {|n| n + 10}
a.find {|n| n > 4}
a.inject {|acc,n| acc + n}
a.class
a.class.ancestors

Moduł Enumerable

pr = [1.3, 2.5, 4.1, 1.8]
pr.max
pr.min
pr.map! {|n| n.to_s}
a = [*1..10]
a.group_by {|x| x % 2}  # 1.9, yields a hash
class Person
  attr_reader :age
  def initialize(age)
    @age = age
  end
  def <=>(other)
    self.age <=> other.age
  end
end
a = Person.new(20)
b = Person.new(30)
c = Person.new(30)
d = Person.new(25)
[a,b,c,d].sort.group_by {|person| person.age}  # 1.9
[a,b,c,d].sort.group_by(&:age)                 # 1.9
a = [*1..10]
a.each_cons(3) {|cons| p cons }
a.each_slice(3) {|cons| p cons }
a.each_cons(3).map {|x,y,z| x * y * z }
nums = [1.2, 2.3, 1.8, 5.2, 3.5]
nums.any? {|n| n < 1}   # false
nums.all? {|n| n < 10}  # true
nums.sort
nums.sort.take(2)  # 1.9
nums.sort.drop(2)  # 1.9
nums.sort.take_while {|n| n < 3}  # 1.9

Gemy

puts $:  # bez ścieżek do bibliotek rubygems w 1.8

Napisy

str = "ala ma kota"
str[2]   # 97, ruby 1.8
str[2,1] # "a"
str[2]   # "a", ruby 1.9
?a       # 97, ruby 1.8
?a       # "a", ruby 1.9
?a.ord   # 97

W 1.9 napisy nie są Enumerable, tj. str.each nie działa. Za to mamy:

str.each_char   str.chars
str.each_byte   str.bytes
mstr = "hello\nworld"
mstr.each_line {|l| puts l.upcase}
str.chars.to_a  # ["a", "l", "a", ...]

Kodowanie

str = "witaj świecie'
str.encoding

Zadawanie kodowania w pliku via magic comments:

# *coding: utf-8*

Ruby misz masz

str = "ala ma kota"           # 1.8
str.instance_eval { upcase }
str.instance_eval { split }
str.instance_exec(/a/) {|re| split(re) }  # 1.9