2012-03-07 77 views
0

我正在學習Ruby Proc類。我不明白爲什麼執行「def state =」方法。瞭解proc類

我也想知道爲什麼「t1.state = 1」結了「高清狀態=(1)」

我不明白「高清狀態」和「高清狀態=」之間的區別?

我可以理解這個連接「& 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) 
+2

'def state'是getter,而'def state =(state)'是setter – fl00r 2012-03-07 17:10:19

+0

setter/getter ...是如何設置屬性並使用它。我能夠了解。謝謝fl00r – Bamboo 2012-03-08 22:41:17

回答

0

該表達式:

Terminal.new.state = 1 

將調用方法def state=(current)

而這種表達

puts Terminal.new.state 

將調用方法def state或讀出的數據

+0

謝謝,megas。最後我提出了理解。 – Bamboo 2012-03-08 22:16:42