0
votes

I am studying Ruby Proc class. I don't understand why "def state="method is executed.

I also want to know why "t1.state = 1" end up with "def state=(1)"

I don't understand difference between "def state" and "def state=" ?

I can understand this connection "&proc>proc>proc.call".

    # -*- coding: utf-8 -*-
    class Terminal
      def initialize
        @connected = []
        @current_state = nil
      end
      def connect(&proc)
        @connected << proc
      end
      def current_input_terminal(terminal)
        connect do |hoge|
          terminal.state = hoge
        end
      end
      def state=(current)
        if current != 0 && current != 1
          raise(ArgumentError, "input 0 or 1")
        end
        if @current_state != current
          @current_state = current
          @connected.each do |i|
            i.call(current)
          end
        end
      end
      def state
        @current_state
      end
    end

    t1 = t2 = Terminal.new()
    t1.current_input_terminal(t2)
    t1.state = 1
    puts(t2.state,t1.state)
1
def state is getter while def state=(state) is setter - fl00r
setter/getter... is how to set property & use it. I can understand. Thank you fl00r - Bamboo

1 Answers

0
votes

This expression:

Terminal.new.state = 1

will call method def state=(current)

And this expression

puts Terminal.new.state 

will call method def state or read the data