Never been to CodeSnippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world (or not, you can keep them private!)

About this user

Pavel http://users.livejournal.com/9__/

Сортировка массива с городами

// К примеру мне нужен массив с городами(имя, год основания). Отсортировать его(по году основания) и вывести названия городов.
// Чтобы отсортировать массив по населению, надо лишь заменить year на population)

cities = Array.new
cities << { :name => 'SPb',    :year => 1703, :population => 5_000_000 }
cities << { :name => 'Moscow', :year => 1147, :population => 10_000_000_000 }

cities.sort_by { |city| city[:year] }.each do |city|
  puts "#{city[:name]}"
end

Интересное использование default params

// http://blog.floehopper.org/presentations/lrug-mock-objects-2007-07-09/
# def started?(clock = Clock.new)

class Clock
  def time
    Time.now
  end
end

class Event
  def initialize(start_time)
    @start_time = start_time
  end
  
  def started?(clock = Clock.new)
    clock.time > @start_time
  end  
end

Округлить дробное число до двух разрядов

gpo6Hoe_4ucJIo = 3.1415926535
puts ( gpo6Hoe_4ucJIo * 100 ).to_i.to_f / 100
puts sprintf( "%.2f", gpo6Hoe_4ucJIo ).to_f    # предпочтительнее, так как действительно округляет

Cmd-console utf unicode encoding solution

$KCODE = "utf-8"
STDIN.encoding = "utf-8"