Разве это не просто ...
word_list=['Jellicle', 'Cats', 'are', 'black', 'and', 'white,', 'Jellicle', 'Cats',
'are', 'rather', 'small;', 'Jellicle', 'Cats', 'are', 'merry', 'and',
'bright,', 'And', 'pleasant', 'to', 'hear', 'when', 'they', 'caterwaul.',
'Jellicle', 'Cats', 'have', 'cheerful', 'faces,', 'Jellicle', 'Cats',
'have', 'bright', 'black', 'eyes;', 'They', 'like', 'to', 'practise',
'their', 'airs', 'and', 'graces', 'And', 'wait', 'for', 'the', 'Jellicle',
'Moon', 'to', 'rise.', '']
from collections import Counter
c = Counter(word_list)
c.most_common(3)
Который должен выводить
[('Jellicle', 6), ('Cats', 5), ('are', 3)]
Проще всего использовать : if
следующим образом:
class User < ActiveRecord::Base
validate_presence_of :name
validate_presence_of :age, :if => Proc.new { |user| user.signup_step >= 2 }
# ... etc
end
или:
class User < ActiveRecord::Base
validate_presence_of :name
validate_presence_of :age, :if => :registering?
def registering?
signup_step >= 2
end
end
Вы также можете использовать метод validate
для определения любого сложная, нестандартная логика. Например:
class User < ActiveRecord::Base
validate :has_name_and_email_after_invitation
validate :has_complete_profile_after_registration
def has_name_and_email_after_invitation
if ... # determine if we're creating an invitation
# step 1 validation logic here
end
end
def has_complete_profile_after_registration
if ... # determine if we're registering a new user
# step 2 validation logic here
end
end
end
(В приведенном выше примере вы могли бы фактически определить правила проверки в has_name_and_email_after_invitation
с помощью обычных вызовов validates_xxx_of
, потому что они должны применяться и на шаге 2, но с использованием два метода для отдельных шагов обеспечивают максимальную гибкость.)
И для DRYin'up немного кода, вы можете использовать with_options
, например:
class Example < ActiveRecord::Base
[...]
def registering?
signup_step >= 2
end
with_options(:if => :registering?) do |c|
c.validates_presence_of :name
end
with_options(:unless => :registering?) do |c|
c.validates_presence_of :contact_details
end
[...]
end
Подробнее о with_options
здесь :
http://apidock.com/rails/v2.3.2/Object/with_options
Есть даже скринкаст от RailsCasts: