2013-12-16 10 views
-1

我想創建是一個程序,將允許用戶輸入一個名字,這個名字會給在兩個不同文件中的兩個消息。第二個文件中的消息只是輸入的名稱。特別是我自學的是涉及子類的公共類方法,我在下面的程序中嘗試這樣做。任何建議或鏈接將不勝感激。調試器說這是一個語法錯誤行37(最後一行)「意外的$結束,期待key_word結束」。在Ruby中如何用子類創建方法?

puts "Hello Friend. What is your name?" 
    STDOUT.flush 
$end 

def self.get 
    name 
end 

def self.name 
    name = gets.chomp 
end 

File.open("testingruby.doc", 'w') do |file| 
    if name != "David" 
    file.puts "That's incorrect." + " " + name 
    else 
    file.puts "Hello " + name + "!" + " I hope you are well. Welcome to Ruby." 
end 

public_class_method :name 
$end 



class ExampleTwo < ExampleOne 
def self.get 
    pizza 
end 

def self.pizza 
    piza = name 
end 

File.open("testingruby2.doc", 'w') do |file2| 
    file2.puts(pizza) 
end 
end 
+1

這是所有的代碼? '$ end'是什麼?定義的全局'$ end'在哪裏?爲什麼你總是得到它的價值? – Linuxios

+0

我想這不是完整的代碼。我也會有興趣瞭解方法調用和'$ end'的原因。 – zeantsoi

+0

所有'$ end's的其實只是全局變量的訪問被返回nil,因爲沒有全局變量'$ end'。所以真的,它們只是一堆價值爲零的線。 – Linuxios

回答

0

你的File.open第一次調用缺少一個end到塊:

File.open("testingruby.doc", 'w') do |file| 
    if name != "David" 
    file.puts "That's incorrect." + " " + name 
    else 
    file.puts "Hello " + name + "!" + " I hope you are well. Welcome to Ruby." 
    end 
end 

請記住,Ruby的條件語句必須顯式地關閉。從外觀上來看,你試圖關閉File.open塊不關閉條件第一,這是造成你的問題。

+0

感謝您的評論。你的建議,現在它說:「未定義的方法'public_class_method'爲主:對象」。有關如何解決此問題的任何建議或鏈接? – David

+0

'public_class_method'的用途是什麼?如果你不知道爲什麼它在那裏,你應該完全刪除它。如果您對語法有疑問:從外觀上看,您試圖調用一個名爲'public_class_method'的方法並將':name'符號傳遞給它。如果你在代碼的其他地方定義了方法,你將不會收到這個錯誤......如果你沒有定義它,你需要定義它,或者2)刪除它。 – zeantsoi

+0

是的,那是我正在嘗試做的事(「調用一個名爲public_class_method的方法並將名稱符號傳遞給它」),因爲我有第二個類,我試圖通過輸入的名稱來輸入名稱顯示在第二個.doc文件中。該程序按原樣將輸入的名稱放入第一個類中顯示的同一文件中。我的理解是發生這種方法和符號必須是公開的。它是否正確? – David

0

正如我在你的問題的評論中提到的,我浪費了回答您剛纔的問題相當長的時間(這一個輕微的變體),你之前,我曾試圖發佈我的解決方案,實際上刪除,拉從我腳下的地毯。我的答案的第一部分解釋了代碼中的一些問題。這消失了,我不想重新創建它。下面是我保留的第二部分。這是一個建議,做你想達到什麼:

class ExampleOne 
    def self.name 
    puts "Hello Friend. What is your name?" 
    your_name = gets.chomp 
    if your_name != "David" 
     str = "That's incorrect," + " " + your_name + "." 
    else 
     str = "Hello " + your_name + "!" + \ 
     " I hope you are well. Welcome to Ruby." 
    end 
    File.write("testingruby.doc", str) 
    File.write("testingruby2.doc", your_name) 
    end 
end 

我們可以通過運行其測試內容並閱讀它創建的文件的內容:

ExampleOne.name # Enter "Doug" 
puts File.read("testingruby.doc") # => That's incorrect, Doug. 
puts File.read("testingruby2.doc") # => Doug 

ExampleOne.name # Enter "David" 
puts File.read("testingruby.doc") 
    # => Hello David! I hope you are well. Welcome to Ruby. 
puts File.read("testingruby2.doc") # => David 

相反的File.write我能有書面:

File.open("testingruby.doc", 'w') do |file| 
    file.write(str) 
    file.close 
    end 

這裏file.close是可選的;在任何情況下,文件將在塊的結尾處關閉。類似的,而不是File.read你可以寫:

File.open("testingruby.doc", 'r') do |file| 
    puts file.read 
    file.close 
    end 

,並再次,不需要file.close

+0

感謝您的時間和考慮。我對發生的事情表示歉意。 – David

相關問題