A
A
Anton Filippov2014-05-17 21:15:43
ruby
Anton Filippov, 2014-05-17 21:15:43

How to write a mutator method in ruby?

Surprisingly, I couldn't find an answer on Google.

def sqr!(a) # Объявляем метод
  a **= 2
end

b = 5 # Присваиваем значение переменной
sqr! b # Передаём её вышеобъявленному методу
b # Проверяем значение (выводится 5, как сделать чтобы возвращалось 25?)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Viktor Vsk, 2014-05-17
@viktorvsk

The first thing is on the Internet ( www.velocityreviews.com/forums/t814224-creating-ba... ):

class MyNumber
def initialize( initialValue=nil )
@n = initialValue || 0
end

def abs!
@n = @n.abs
end

def method_missing(meth, *args, &block) # :nodoc:
@n.send(meth, *args, &block)
end
end

Further, I think it depends on the specific context of the task.
You can check like this:
a = MyNumber.new -5
a.abs!
a

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question