Name of a symbol in ruby

I’m very new to ruby. I have to code in ruby at work and a coworker gave me some tests he wrote in ruby. I have some difficulties to understand a line he wrote.

We have a class like this:

class Port
    attr_accessor :nature, :name

    def initialize(name)
        @name = name

The test consists in:

x_port ="x")
x_port.nature = :sampling
x_port.wont_be_nil :sampling

I have some trouble to understand the last line, the I understand that we are demanding the name of the symbol but this method doesn’t exist and I can’t create a method name name because of the symbol :name already there. Can someone enlighten me of how to resolve this problem?

Thanks a lot

Sorry but this ‘problem’ doesn’t make much sense. It is either intentionally confusing or there is just some kind of typo.

It is possible in Ruby to open a class and add new methods, like

class Symbol
  def name

which would basically allow x_port.nature to return its current value as seems expected in the tests.

This as such would be well worth learning. But putting it into an example where there is another name method even if not directly related seems not very smart. So either it’s a stupid ‘trick’ or as said just a typo and the test should look like

x_port.nature.must_equal :sampling

and then there should be more tests that run on which is also defined in parallel to nature and its value set to “x” in the initializer.

Trả lời

Email của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *