[英]Ruby: Calling a method from another method that needs an attribute
基本上,我有兩種方法和一個數組。 我正在設置一個 CLI 界面。 我有一種方法“調用”,它貫穿其他方法。 一種這樣的方法需要一個論據。 所有這些方法都在同一個 class 中。
class CLI
array = ["test"]
def method_2
method_1
end
def method_1(array)
puts array
end
end
我想上面給output這個數組。 但是,當我調用 class 的新實例時,我得到了錯誤的 arguments 編號。 我不知道在哪里添加所需的 arguments。
感謝您的時間。
-M
通常在面向 object 的設計中,您將數據和作用於數據的方法封裝在 object 中。 在 Ruby 中,您可以使用實例變量創建 object 的屬性:
class CLI
def initialize(array = [])
@array = []
end
def method_2
method_1
end
def method_1
puts @array
end
end
cli = CLI.new(["Hello", "World"])
cli.method2
實例變量使用印記@
。 它們被認為是私有的,因為它們的范圍是實例,即使 Ruby 沒有對實例變量使用private
關鍵字。
類也可以有實例變量:
class CLI
@array = ["Hello", "World"]
def self.hello
puts @array.join(" ")
end
def you_cant_access_it_from_an_instance
@array
end
end
CLI.hello # Hello World
CLI.new.you_cant_access_it_from_an_instance # nil
這是屬於 class 本身的“類”實例變量 - 它不與子類共享。 這有效,因為在 Ruby 類是對象 - Class class 的實例。
Ruby 還具有 class 變量,這些變量在 class 及其所有后代之間共享:
class Foo
@@array = ["Hello", "World"]
def self.hello
puts @@array.join(" ")
end
def self.array=(val)
@@array = val
end
end
class Bar < Foo; end
Bar.array = ['Oh', 'noes']
Foo.hello # Oh noes
它們在線程安全方面存在嚴重問題,最好避免由於意外行為。
我相信你正在做的一個常見模式是一個工廠方法,它使用它的輸入創建一個新實例,然后調用它的調用方法:
class CLI
def initialize(*args)
@args = args
end
def call
puts @args.inspect
# do something awesome
end
# factory method thats basically just a convenience
def self.call(*args)
new(args).call
end
end
CLI.call(*ARGV) # passes the command line arguments
我不清楚你想要做什么,但聽起來你想要的是至少有一個(或多個)方法來打印出變量的當前值,但你沒有'不想在調用它們時將該變量作為參數傳遞給這些方法。
您無法通過定義默認參數(例如def method_1(array=['test'])
來實現這一點,因為該默認參數僅在定義方法時評估一次,並且該默認值將永遠是方法首先被定義(它沒有得到更新)。
因此,將您的代碼更改為如下所示:
class CLI
@@array = ["test"]
def method_2
method_1
end
def method_1
puts @@array
end
end
@@
前綴表示 class 變量: class 的所有實例將共享該變量的相同值。 然后確保@@array
的值保持最新。 您可能想要重新設計您的程序,但除了風格和最佳實踐問題外,您總有一個答案。
執行此操作的正常方法是在調用method_1
時將參數傳遞給它,但是如果您希望method_2
調用method_1
而您不想將其作為參數傳遞給method_2
,那么您就有點過時了選項(這就是為什么我說你可能想要重新設計你的界面)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.