attr_initializer

Краен срок
21.11.2014 12:00

Срокът за предаване на решения е отминал

Class Macros

Често използван идиом в Ruby са така наречените клас макроси. Това предизвикателство ще ви даде възможност да имплементирате свое такова.

Най-известният пример за използване на клас макроси са attr_accessor, attr_reader, attr_writer, пример.

Задачата ви е да разширите Class с макро attr_initializer. То трябва да приема произволен брой символи като аргументи и да се използва в класове, в които с аргументите на initialize се инициализират атрибути със същите имена.

Пример:

class Point
  attr_initializer :x, :y
  attr_reader     :x, :y
end

Горната дефиниция трябва да е еквивалентна на

class Point
  attr_reader :x, :y

  def initialize(x, y)
    @x, @y = x, y
  end
end

Нека при подаване на грешен брой аргументи при инициализиране на обект от клас, използващ това макро, да се вдига ArgumentError. Очакваме съобщението на грешката да е стандартното такова за подаване на грешен брой аргументи: "wrong number of arguments (number of passed arguments here for number of expected arguments here)".

Примерен тест

За информация как да изпълните примерния тест, погледнете GitHub хранилището с домашните.

Решения

Емилиан Станков
  • Коректно
  • 4 успешни тест(а)
  • 0 неуспешни тест(а)
Емилиан Станков
class Class
def attr_initializer(*args)
instance_vars = args.map { |arg| "@#{arg.to_s}" }.join(', ')
arguments = args.join(', ')
self.class_eval("def initialize(#{arguments}); #{instance_vars} = #{arguments}; end")
end
end
....

Finished in 0.00834 seconds
4 examples, 0 failures
Людмила Савова
  • Коректно
  • 4 успешни тест(а)
  • 0 неуспешни тест(а)
Людмила Савова
def attr_initializer(*args)
self.class_eval( "def initialize(#{args.join(', ')})
#{args.map{ |arg| "@#{arg}" }.join(', ')} = #{args.join(', ')}
end" )
end
....

Finished in 0.0068 seconds
4 examples, 0 failures
Мартина Радева
  • Коректно
  • 4 успешни тест(а)
  • 0 неуспешни тест(а)
Мартина Радева
class Module
def attr_initializer(*field_names)
begin
self.class_eval do
define_method :initialize do |*values|
if field_names.length == values.length
hash = Hash[field_names.zip(values)]
hash.each{ |field, value| instance_variable_set("@#{field}", value) }
else raise ArgumentError, "wrong number of arguments (#{values.length} for #{field_names.length})"
end
end
end
end
end
end
....

Finished in 0.00673 seconds
4 examples, 0 failures
Гюлджан Купен
  • Коректно
  • 4 успешни тест(а)
  • 0 неуспешни тест(а)
Гюлджан Купен
class Class
def attr_initializer(*arguments)
define_method :initialize do |*values|
if values.count == arguments.count
arguments.zip(values).each do |name, value|
instance_variable_set "@#{name}".to_sym, value
end
else
raise ArgumentError, "wrong number of arguments (#{values.count} for #{arguments.count})"
end
end
end
end
....

Finished in 0.00682 seconds
4 examples, 0 failures
Александър Александров
  • Коректно
  • 4 успешни тест(а)
  • 0 неуспешни тест(а)
Александър Александров
class Class
def attr_initializer (*method_arguments)
define_method (:initialize) do |*arguments|
if method_arguments.length != arguments.length
raise ArgumentError.new("wrong number of arguments (#{arguments.length} for #{method_arguments.length})")
end
method_arguments.zip(arguments).each do |method_arguments, arguments|
instance_variable_set :"@#{method_arguments}", arguments
end
end
end
end
....

Finished in 0.00803 seconds
4 examples, 0 failures
Йоана Тодорова
  • Коректно
  • 4 успешни тест(а)
  • 0 неуспешни тест(а)
Йоана Тодорова
class Class
def attr_initializer(*symbols)
module_eval do
define_method :initialize do |*values|
if values.count != symbols.count
raise ArgumentError,
"wrong number of arguments (#{values.count} for #{symbols.count})"
end
symbols.zip(values).each do |symbol, value|
instance_variable_set("@#{symbol}", value)
end
end
end
end
end
....

Finished in 0.00683 seconds
4 examples, 0 failures
Габриела Лухова
  • Коректно
  • 4 успешни тест(а)
  • 0 неуспешни тест(а)
Габриела Лухова
class Class
def attr_initializer(*args)
define_method :initialize do |*values|
args.zip(values).each do |arg, value|
instance_variable_set("@#{arg}", value)
end
message = "wrong number of arguments (#{values.size} for #{args.size})"
raise ArgumentError, message unless args.size == values.size
end
end
end
....

Finished in 0.00679 seconds
4 examples, 0 failures
Екатерина Горанова
  • Коректно
  • 4 успешни тест(а)
  • 0 неуспешни тест(а)
Екатерина Горанова
class Class
def attr_initializer(*attrs)
initialize = ->(*args) do
if not args.size.eql? attrs.size
raise ArgumentError, "wrong number of arguments (#{args.size} for #{attrs.size})"
end
attrs.zip(args).each do |name, value|
instance_variable_set("@#{name}", value)
end
end
define_method(:initialize, &initialize)
end
end
....

Finished in 0.00681 seconds
4 examples, 0 failures
Мая Терзиева
  • Коректно
  • 4 успешни тест(а)
  • 0 неуспешни тест(а)
Мая Терзиева
class Class
def attr_initializer(*variables)
define_method :initialize do |*arguments|
if variables.length != arguments.length
raise ArgumentError.new("wrong number of arguments (#{arguments.length} for #{variables.length})")
else
variables.zip(arguments).each do |name, value|
instance_variable_set("@#{name}", value)
end
end
end
end
end
....

Finished in 0.00674 seconds
4 examples, 0 failures
Константин Тодоров
  • Коректно
  • 4 успешни тест(а)
  • 0 неуспешни тест(а)
Константин Тодоров
class Class
def attr_initializer(*args)
define_method (:initialize) do |*arguments|
raise ArgumentError, "wrong number of arguments (#{ arguments.size } for #{ args.size })" if (args.size != arguments.size)
i = 0
args.each do |argument|
instance_variable_set "@#{ argument }", arguments[i]
i += 1
end
end
end
end
....

Finished in 0.00683 seconds
4 examples, 0 failures
Диана Генева
  • Коректно
  • 4 успешни тест(а)
  • 0 неуспешни тест(а)
Диана Генева
class Class
def attr_initializer(*arguments)
define_method(:initialize) do |*variables|
unless variables.size == arguments.size
raise(ArgumentError,
"wrong number of arguments (#{variables.size} for #{arguments.size})")
end
arguments.zip(variables).each do |argument, variable|
instance_variable_set("@#{argument}", variable)
end
end
end
end
....

Finished in 0.00678 seconds
4 examples, 0 failures
Деян Гюрджеклиев
  • Коректно
  • 4 успешни тест(а)
  • 0 неуспешни тест(а)
Деян Гюрджеклиев
class Class
def attr_initializer(*args)
self.class_eval do
define_method(:initialize) do |*values|
raise ArgumentError, "wrong number of arguments (#{values.size} for #{args.size})" unless values.size == args.size
args.each_with_index do |arg, index|
instance_variable_set("@#{arg}", values[index])
end
end
end
end
end
....

Finished in 0.00774 seconds
4 examples, 0 failures
Ангел Ангелов
  • Коректно
  • 4 успешни тест(а)
  • 0 неуспешни тест(а)
Ангел Ангелов
class Class
def attr_initializer(*names)
body = 'def initialize('
body += names.join(', ')
body += '); '
names.map(&:to_s).each { |name| body += '@' + name + ' = ' + name + '; ' }
body += 'end'
class_eval body
end
end
....

Finished in 0.00685 seconds
4 examples, 0 failures
Бисер Кръстев
  • Коректно
  • 4 успешни тест(а)
  • 0 неуспешни тест(а)
Бисер Кръстев
class Class
def attr_initializer(*variables)
count = variables.length
define_method(:initialize) do |*args|
raise ArgumentError.new("wrong number of arguments (#{args.length} for #{count})") unless args.length == count
variables.each_with_index { |variable, index| instance_variable_set("@#{variable}", args[index]) }
end
end
end
....

Finished in 0.0075 seconds
4 examples, 0 failures
Атанас Димитров
  • Некоректно
  • 0 успешни тест(а)
  • 0 неуспешни тест(а)
Атанас Димитров
class Class
def attr_initializer(x, y)
class_eval("def initialize(x, y)
@#{x} = x
@#{y} = y
end")
end
end
/tmp/d20141122-26053-srql2u/solution.rb:2:in `attr_initializer': wrong number of arguments (3 for 2) (ArgumentError)
	from /tmp/d20141122-26053-srql2u/spec.rb:13:in `<class:Person>'
	from /tmp/d20141122-26053-srql2u/spec.rb:12:in `block in <top (required)>'
	from /data/rails/evans-2014/shared/bundle/ruby/2.1.0/gems/rspec-core-2.14.7/lib/rspec/core/example_group.rb:246:in `module_eval'
	from /data/rails/evans-2014/shared/bundle/ruby/2.1.0/gems/rspec-core-2.14.7/lib/rspec/core/example_group.rb:246:in `subclass'
	from /data/rails/evans-2014/shared/bundle/ruby/2.1.0/gems/rspec-core-2.14.7/lib/rspec/core/example_group.rb:232:in `describe'
	from /data/rails/evans-2014/shared/bundle/ruby/2.1.0/gems/rspec-core-2.14.7/lib/rspec/core/dsl.rb:18:in `describe'
	from /tmp/d20141122-26053-srql2u/spec.rb:1:in `<top (required)>'
	from /data/rails/evans-2014/shared/bundle/ruby/2.1.0/gems/rspec-core-2.14.7/lib/rspec/core/configuration.rb:896:in `load'
	from /data/rails/evans-2014/shared/bundle/ruby/2.1.0/gems/rspec-core-2.14.7/lib/rspec/core/configuration.rb:896:in `block in load_spec_files'
	from /data/rails/evans-2014/shared/bundle/ruby/2.1.0/gems/rspec-core-2.14.7/lib/rspec/core/configuration.rb:896:in `each'
	from /data/rails/evans-2014/shared/bundle/ruby/2.1.0/gems/rspec-core-2.14.7/lib/rspec/core/configuration.rb:896:in `load_spec_files'
	from /data/rails/evans-2014/shared/bundle/ruby/2.1.0/gems/rspec-core-2.14.7/lib/rspec/core/command_line.rb:22:in `run'
	from /data/rails/evans-2014/shared/bundle/ruby/2.1.0/gems/rspec-core-2.14.7/lib/rspec/core/runner.rb:80:in `run'
	from /data/rails/evans-2014/shared/bundle/ruby/2.1.0/gems/rspec-core-2.14.7/lib/rspec/core/runner.rb:17:in `block in autorun'
Светлозар Стефанов
  • Коректно
  • 4 успешни тест(а)
  • 0 неуспешни тест(а)
Светлозар Стефанов
class Class
def attr_initializer(*arguments)
define_method(:initialize) do |*args|
if arguments.size != args.size
message = "wrong number of arguments (#{args.size} for #{arguments.size})"
raise ArgumentError, message
end
temp = 0
arguments.each do |item|
instance_variable_set("@#{item}", args[temp])
temp += 1
end
end
end
end
....

Finished in 0.0067 seconds
4 examples, 0 failures
Венцислав Димитров
  • Коректно
  • 4 успешни тест(а)
  • 0 неуспешни тест(а)
Венцислав Димитров
class Class
def attr_initializer(*vars)
self.class_eval do
define_method :initialize do |*args|
if (args.size != vars.size)
raise ArgumentError.new("wrong number of arguments (#{args.size} for #{vars.size})")
end
vars.each_with_index.map{|var, i| instance_variable_set "@#{var}", args[i]}
end
end
end
end
....

Finished in 0.00681 seconds
4 examples, 0 failures
Камен Станев
  • Коректно
  • 4 успешни тест(а)
  • 0 неуспешни тест(а)
Камен Станев
class Class
def attr_initializer(*attr_names)
define_method('initialize') do |*init_args|
if init_args.size != attr_names.size
raise ArgumentError, "wrong number of arguments (#{init_args.size} for #{attr_names.size})"
end
attr_names.zip(init_args).each do |name, value|
instance_variable_set("@#{name}", value)
end
end
end
end
....

Finished in 0.00962 seconds
4 examples, 0 failures
Нели Василева
  • Коректно
  • 4 успешни тест(а)
  • 0 неуспешни тест(а)
Нели Василева
class Class
def attr_initializer(*variables)
define_method(:initialize) do |*values|
raise ArgumentError.new("wrong number of arguments (#{values.size} for #{variables.size})") if values.size != variables.size
([] << variables << values).transpose.each do |variable, value|
instance_variable_set "@#{variable}", value
end
end
end
end
....

Finished in 0.00681 seconds
4 examples, 0 failures
Теодор Драганов
  • Некоректно
  • 0 успешни тест(а)
  • 0 неуспешни тест(а)
Теодор Драганов
class Class
def attr_initializer(x, y)
self.class_eval { def initialize(x, y); @x, @y = x, y; end }
end
end
/tmp/d20141122-26053-cjz3p8/solution.rb:2:in `attr_initializer': wrong number of arguments (3 for 2) (ArgumentError)
	from /tmp/d20141122-26053-cjz3p8/spec.rb:13:in `<class:Person>'
	from /tmp/d20141122-26053-cjz3p8/spec.rb:12:in `block in <top (required)>'
	from /data/rails/evans-2014/shared/bundle/ruby/2.1.0/gems/rspec-core-2.14.7/lib/rspec/core/example_group.rb:246:in `module_eval'
	from /data/rails/evans-2014/shared/bundle/ruby/2.1.0/gems/rspec-core-2.14.7/lib/rspec/core/example_group.rb:246:in `subclass'
	from /data/rails/evans-2014/shared/bundle/ruby/2.1.0/gems/rspec-core-2.14.7/lib/rspec/core/example_group.rb:232:in `describe'
	from /data/rails/evans-2014/shared/bundle/ruby/2.1.0/gems/rspec-core-2.14.7/lib/rspec/core/dsl.rb:18:in `describe'
	from /tmp/d20141122-26053-cjz3p8/spec.rb:1:in `<top (required)>'
	from /data/rails/evans-2014/shared/bundle/ruby/2.1.0/gems/rspec-core-2.14.7/lib/rspec/core/configuration.rb:896:in `load'
	from /data/rails/evans-2014/shared/bundle/ruby/2.1.0/gems/rspec-core-2.14.7/lib/rspec/core/configuration.rb:896:in `block in load_spec_files'
	from /data/rails/evans-2014/shared/bundle/ruby/2.1.0/gems/rspec-core-2.14.7/lib/rspec/core/configuration.rb:896:in `each'
	from /data/rails/evans-2014/shared/bundle/ruby/2.1.0/gems/rspec-core-2.14.7/lib/rspec/core/configuration.rb:896:in `load_spec_files'
	from /data/rails/evans-2014/shared/bundle/ruby/2.1.0/gems/rspec-core-2.14.7/lib/rspec/core/command_line.rb:22:in `run'
	from /data/rails/evans-2014/shared/bundle/ruby/2.1.0/gems/rspec-core-2.14.7/lib/rspec/core/runner.rb:80:in `run'
	from /data/rails/evans-2014/shared/bundle/ruby/2.1.0/gems/rspec-core-2.14.7/lib/rspec/core/runner.rb:17:in `block in autorun'
Атанас Цанков
  • Коректно
  • 4 успешни тест(а)
  • 0 неуспешни тест(а)
Атанас Цанков
class Class
def attr_initializer(*names)
define_method(:initialize) do |*values|
raise ArgumentError.new("wrong number of arguments (#{values.size} for #{names.size})") unless values.size == names.size
names.each_with_index { |a, i| instance_variable_set("@#{a}", values.fetch(i)) }
end
end
end
....

Finished in 0.00681 seconds
4 examples, 0 failures
Николина Гюрова
  • Коректно
  • 4 успешни тест(а)
  • 0 неуспешни тест(а)
Николина Гюрова
class Object
def attr_initializer(*attr)
define_method :initialize do |*args|
if attr.size != args.size
raise ArgumentError, "wrong number of arguments (#{args.size} for #{attr.size})"
end
attr.each_with_index do |attribute, index|
instance_variable_set("@#{attribute}", args[index])
end
end
end
end
....

Finished in 0.00686 seconds
4 examples, 0 failures
Стилиян Стоянов
  • Коректно
  • 4 успешни тест(а)
  • 0 неуспешни тест(а)
Стилиян Стоянов
class Module
def attr_initializer(*attrs)
class_eval do
define_method :initialize do |*args|
if (attrs.length != args.length)
raise ArgumentError, "wrong number of arguments (#{args.length} for #{attrs.length})"
end
attrs.zip(args).each do |attr, val|
instance_variable_set("@#{attr}", val)
end
end
end
end
end
....

Finished in 0.008 seconds
4 examples, 0 failures
Любослава Димитрова
  • Коректно
  • 4 успешни тест(а)
  • 0 неуспешни тест(а)
Любослава Димитрова
class Class
def attr_initializer(*args)
define_method("initialize") do |*values|
unless args.length != values.length
args.zip(values){|arg, val| instance_variable_set("@#{arg}", val)}
else
raise ArgumentError, "wrong number of arguments (#{values.length.to_s} for #{args.length.to_s})"
end
end
end
end
....

Finished in 0.00689 seconds
4 examples, 0 failures
Ясен Трифонов
  • Коректно
  • 4 успешни тест(а)
  • 0 неуспешни тест(а)
Ясен Трифонов
class Class
def attr_initializer(*args)
setters = args.map { |arg| "@#{arg}" } .join(',')
arg_error = "raise ArgumentError, \"wrong number of arguments (\#{args.length} for #{args.length})\""
class_eval "def initialize(*args); #{arg_error} unless args.length == #{args.length}; #{setters} = *args; end"
end
end
....

Finished in 0.00666 seconds
4 examples, 0 failures
Дамян Димитров
  • Коректно
  • 4 успешни тест(а)
  • 0 неуспешни тест(а)
Дамян Димитров
class Class
def attr_initializer(*vars)
instance_vars = vars.map { |var| "@#{var}".to_sym}
define_method :initialize do |*args|
unless instance_vars.size == args.size
fail ArgumentError, "wrong number of arguments (#{args.size} for #{instance_vars.size})"
end
instance_vars.each_with_index { |var, index| instance_variable_set(var, args[index]) }
end
end
end
....

Finished in 0.00661 seconds
4 examples, 0 failures
Евгений Бояджиев
  • Коректно
  • 4 успешни тест(а)
  • 0 неуспешни тест(а)
Евгений Бояджиев
# # This varsion is the normal one but it will fail with named parameters
# class Class
# def attr_initializer (*arg_names)
# implementation = ->(*args) do
# # validation: the arguments count must match attr_initializer's count
# if args.size != arg_names.size
# error_message =
# "wrong number of arguments" +
# " (#{args.size} for #{arg_names.size})"
# raise ArgumentError.new(error_message)
# end
# # set the values
# arg_names.each_with_index do |name, index|
# instance_variable_set "@#{name}", args[index]
# end
# end
# define_method("initialize", &implementation)
# end
# end
# This varsion is the extended one: it works for named parameters
# and will throw an ArgumentError if one of the names is incorrect
class Class
def attr_initializer (*arg_names)
implementation = ->(*args, **kargs) do
# validation: the arguments count must match attr_initializer's count
if args.size + kargs.size != arg_names.size
error_message =
"wrong number of arguments" +
" (#{args.size + kargs.size} for #{arg_names.size})"
raise ArgumentError.new(error_message)
end
# validation: the named arguments must have analogs in attr_initializer
kargs.each do |name, _|
unless arg_names.include?(name)
error_message = "unknown name of a parameter (#{name})"
raise ArgumentError.new(error_message)
end
end
# set the values
arg_index = 0
arg_names.each do |name|
if kargs.has_key?(name)
val = kargs[name]
else
val = args[arg_index]
arg_index += 1
end
instance_variable_set "@#{name}", val
end
end
define_method("initialize", &implementation)
end
end
# Another way of doing it would be to use class_eval,
# but it looked like an ugly option to me.
# # Additional tests to check specifically for named parameters
# describe "Class.attr_initializer" do
# class Point
# attr_initializer :x, :y
# end
# it "can be used to initialize a Point - parameter order" do
# expect(Point.new(x: 2, y: 8).instance_variable_get("@x")).to eq(2)
# expect(Point.new(x: 1, y: 5).instance_variable_get("@y")).to eq(5)
# end
# it "can be used to initialize a Point - changed order" do
# expect(Point.new(y: 4.2, x: 4).instance_variable_get("@x")).to eq(4)
# expect(Point.new(y: 21.1, x: 2).instance_variable_get("@y")).to eq(21.1)
# end
# it "can be used to detect wrong number of arguments in initialization" do
# expect { Point.new(x: 4) }.to raise_error(ArgumentError).with_message("wrong number of arguments (1 for 2)")
# expect { Point.new(x: 3, y: 4, z: 5) }.to raise_error(ArgumentError).with_message("wrong number of arguments (3 for 2)")
# end
# it "can be used to detect wrong names of arguments in initialization" do
# expect { Point.new(wrong_name: 4.2, x: 4) }.to raise_error(ArgumentError).with_message("unknown name of a parameter (wrong_name)")
# end
# end
....

Finished in 0.00744 seconds
4 examples, 0 failures
Любомир Петков
  • Коректно
  • 4 успешни тест(а)
  • 0 неуспешни тест(а)
Любомир Петков
class Class
def attr_initializer(*inst_vars)
define_method :initialize do |*args|
iv_count = inst_vars.count
args_count = args.count
unless iv_count == args_count
raise ArgumentError, "wrong number of arguments (#{args_count} for #{iv_count})"
end
inst_vars.zip(args) do |inst_var, arg|
instance_variable_set("@#{inst_var}", arg)
end
end
end
end
....

Finished in 0.00812 seconds
4 examples, 0 failures
Мария Дулева
  • Некоректно
  • 1 успешни тест(а)
  • 3 неуспешни тест(а)
Мария Дулева
class Class
def attr_initializer(*args)
define_method(:initialize) do |*new_args|
if args.length != new_args.length
raise ArgumentError.new("wrong number of arguments (#{new_args.length} for #{args.length})")
end
new_args.zip(args).each do |new_arg, arg|
self.instance_eval("@#{arg} = #{new_arg}")
end
end
end
end
#<FunctionCall:0xb96ae0a0>F.FF

Failures:

  1) Class.attr_initializer can be used for initialization of attributes
     Failure/Error: expect(FunctionCall.new(:display, [2]).function).to eq(:display)
       
       expected: :display
            got: nil
       
       (compared using ==)
     # /tmp/d20141122-26053-1tqpoxm/spec.rb:18:in `block (2 levels) in <top (required)>'
     # ./lib/language/ruby/run_with_timeout.rb:5:in `block (3 levels) in <top (required)>'
     # ./lib/language/ruby/run_with_timeout.rb:5:in `block (2 levels) in <top (required)>'

  2) Class.attr_initializer assigns correct values to fields
     Failure/Error: person = Person.new(22, :male, "Sofia")
     NameError:
       undefined local variable or method `male' for #<Person:0xb96a2a70 @age=22>
     # /tmp/d20141122-26053-1tqpoxm/solution.rb:8:in `instance_eval'
     # /tmp/d20141122-26053-1tqpoxm/solution.rb:8:in `instance_eval'
     # /tmp/d20141122-26053-1tqpoxm/solution.rb:8:in `block (2 levels) in attr_initializer'
     # /tmp/d20141122-26053-1tqpoxm/solution.rb:7:in `each'
     # /tmp/d20141122-26053-1tqpoxm/solution.rb:7:in `block in attr_initializer'
     # /tmp/d20141122-26053-1tqpoxm/spec.rb:28:in `new'
     # /tmp/d20141122-26053-1tqpoxm/spec.rb:28:in `block (2 levels) in <top (required)>'
     # ./lib/language/ruby/run_with_timeout.rb:5:in `block (3 levels) in <top (required)>'
     # ./lib/language/ruby/run_with_timeout.rb:5:in `block (2 levels) in <top (required)>'

  3) Class.attr_initializer doesn't expose attributes with reader/writer macros
     Failure/Error: expect { Assignment.new(:x, 4).target }.to raise_error(NoMethodError)
       expected NoMethodError, got #<NameError: undefined local variable or method `x' for #<Assignment:0xb96a14cc>> with backtrace:
         # /tmp/d20141122-26053-1tqpoxm/solution.rb:8:in `instance_eval'
         # /tmp/d20141122-26053-1tqpoxm/solution.rb:8:in `instance_eval'
         # /tmp/d20141122-26053-1tqpoxm/solution.rb:8:in `block (2 levels) in attr_initializer'
         # /tmp/d20141122-26053-1tqpoxm/solution.rb:7:in `each'
         # /tmp/d20141122-26053-1tqpoxm/solution.rb:7:in `block in attr_initializer'
         # /tmp/d20141122-26053-1tqpoxm/spec.rb:36:in `new'
         # /tmp/d20141122-26053-1tqpoxm/spec.rb:36:in `block (3 levels) in <top (required)>'
         # /tmp/d20141122-26053-1tqpoxm/spec.rb:36:in `block (2 levels) in <top (required)>'
         # ./lib/language/ruby/run_with_timeout.rb:5:in `block (3 levels) in <top (required)>'
         # ./lib/language/ruby/run_with_timeout.rb:5:in `block (2 levels) in <top (required)>'
     # /tmp/d20141122-26053-1tqpoxm/spec.rb:36:in `block (2 levels) in <top (required)>'
     # ./lib/language/ruby/run_with_timeout.rb:5:in `block (3 levels) in <top (required)>'
     # ./lib/language/ruby/run_with_timeout.rb:5:in `block (2 levels) in <top (required)>'

Finished in 0.00849 seconds
4 examples, 3 failures

Failed examples:

rspec /tmp/d20141122-26053-1tqpoxm/spec.rb:17 # Class.attr_initializer can be used for initialization of attributes
rspec /tmp/d20141122-26053-1tqpoxm/spec.rb:27 # Class.attr_initializer assigns correct values to fields
rspec /tmp/d20141122-26053-1tqpoxm/spec.rb:35 # Class.attr_initializer doesn't expose attributes with reader/writer macros
Деян Боиклиев
  • Коректно
  • 4 успешни тест(а)
  • 0 неуспешни тест(а)
Деян Боиклиев
class Module
def attr_initializer(*parameter_names)
define_method("initialize") do |*parameter_values|
if parameter_names.size() != parameter_values.size()
raise ArgumentError, "wrong number of arguments (#{parameter_values.size()} for #{parameter_names.size()})"
end
parameter_names.each_with_index do |name, index|
instance_variable_set("@#{name}", parameter_values[index])
end
end
end
end
....

Finished in 0.00673 seconds
4 examples, 0 failures
Тодор Табаков
  • Коректно
  • 4 успешни тест(а)
  • 0 неуспешни тест(а)
Тодор Табаков
class Class
def attr_initializer(*vars)
define_method :initialize do |*args|
if args.size != vars.size
raise ArgumentError, "wrong number of arguments (#{args.size} for #{vars.size})"
end
vars.zip(args).each do |var, arg|
instance_variable_set:"@#{var}",arg
end
end
end
end
....

Finished in 0.00668 seconds
4 examples, 0 failures
Методи Димитров
  • Коректно
  • 4 успешни тест(а)
  • 0 неуспешни тест(а)
Методи Димитров
class Class
def attr_initializer(*arg_names)
define_method :initialize do |*values|
if arg_names.count != values.count
error_message = "wrong number of arguments (#{values.count} for #{arg_names.count})"
raise ArgumentError, error_message
end
arg_names.each.with_index do |name, index|
instance_variable_set "@#{name}", values[index]
end
end
end
end
....

Finished in 0.0068 seconds
4 examples, 0 failures
Герасим Станчев
  • Некоректно
  • 2 успешни тест(а)
  • 2 неуспешни тест(а)
Герасим Станчев
class Class
def attr_initializer(*args)
args.each do |argument|
self.class_eval(
"def #{argument}\n" +\
"@#{argument} " +\
"end")
end
self.class_eval(
"def initialize(*values)" +\
"if #{args}.size != values.size \n" +\
"raise ArgumentError.new('wrong number of arguments(' + values.size.to_s + ' for #{args.size})')" +\
"end \n" + \
"0.upto(values.size - 1) do" +\
"|index| instance_variable_set('@'.to_s+#{args}[index].to_s, values[index]) " +\
"end " +\
"end")
end
end
.F.F

Failures:

  1) Class.attr_initializer can be used to detect wrong number of arguments in initialization
     Failure/Error: expect { FunctionCall.new(:fail) }.to raise_error(ArgumentError, "wrong number of arguments (1 for 2)")
       expected ArgumentError with "wrong number of arguments (1 for 2)", got #<ArgumentError: wrong number of arguments(1 for 2)> with backtrace:
         # (eval):2:in `initialize'
         # /tmp/d20141122-26053-17vkykb/spec.rb:23:in `new'
         # /tmp/d20141122-26053-17vkykb/spec.rb:23:in `block (3 levels) in <top (required)>'
         # /tmp/d20141122-26053-17vkykb/spec.rb:23:in `block (2 levels) in <top (required)>'
         # ./lib/language/ruby/run_with_timeout.rb:5:in `block (3 levels) in <top (required)>'
         # ./lib/language/ruby/run_with_timeout.rb:5:in `block (2 levels) in <top (required)>'
     # /tmp/d20141122-26053-17vkykb/spec.rb:23:in `block (2 levels) in <top (required)>'
     # ./lib/language/ruby/run_with_timeout.rb:5:in `block (3 levels) in <top (required)>'
     # ./lib/language/ruby/run_with_timeout.rb:5:in `block (2 levels) in <top (required)>'

  2) Class.attr_initializer doesn't expose attributes with reader/writer macros
     Failure/Error: expect { Assignment.new(:x, 4).target }.to raise_error(NoMethodError)
       expected NoMethodError but nothing was raised
     # /tmp/d20141122-26053-17vkykb/spec.rb:36:in `block (2 levels) in <top (required)>'
     # ./lib/language/ruby/run_with_timeout.rb:5:in `block (3 levels) in <top (required)>'
     # ./lib/language/ruby/run_with_timeout.rb:5:in `block (2 levels) in <top (required)>'

Finished in 0.00767 seconds
4 examples, 2 failures

Failed examples:

rspec /tmp/d20141122-26053-17vkykb/spec.rb:22 # Class.attr_initializer can be used to detect wrong number of arguments in initialization
rspec /tmp/d20141122-26053-17vkykb/spec.rb:35 # Class.attr_initializer doesn't expose attributes with reader/writer macros