First, I mentioned in the previous post that the value obtained by the getter can be output with ** instance name.getter method name **. ** I'm sorry I made a mistake. ** When using a variable to which the instance value is assigned, ** variable.getter method name ** will be output.
Below is a post about private methods.
Also, this is the URL that I used as a reference when posting this time. Thank you very much. https://26gram.com/private-protected-in-ruby https://qiita.com/kidach1/items/055021ce42fe2a49fd66
A private method means that the description below private cannot be called from outside the class.
class Fruits
private
def name
puts "Apple"
end
end
apple = Fruits.new
apple.name
Output result
private method `name' called for #<Fruits:0x00007fe767832538> (NoMethodError)
With this description, the instance method is described below from private, so it cannot be output. An error will occur. This is because it cannot be called from outside the class.
In addition, the following description also causes an error.
class Fruits
apple.name
private
def name
puts "Apple"
end
end
apple = Fruits.new
Output result
undefined local variable or method `apple' for Fruits:Class (NameError)
So what is the right thing to do?
Define a method that calls the following description more than private, Call that method from outside the class.
class Fruits
def info
name
end
private
def name
puts "Apple"
end
end
apple = Fruits.new
apple.info
Output result
Apple
You can also call the private methods of the parent class in the child class.
class InfoFruits
private
def name
puts "Apple"
end
end
class Fruits < InfoFruits
def info
name
end
end
apple = Fruits.new
apple.info
Output result
Apple
Finally, using the getter, which is a private method of the parent class, The value is output.
class InfoFruits
private
def name #Getter
@name
end
end
class Fruits < InfoFruits #You cannot inherit a real instance, but you can use the defined instance methods and variables.
def fruit_name(info_fruit_name)
@name = info_fruit_name #Definition of instance variables
end
def info #You are calling the private method name.
name
end
def info_fruit
puts "#{name}" #In the previous post**Instance name.Getter method name**I mentioned that it can be output with
#I'm sorry I made a mistake. When using a variable to which the instance value is assigned**variable.Getter method name**I will output with.
#Since no variables are used this time, it is possible to output in this form.
end
end
apple = Fruits.new #Instance generation
apple.info #I am calling a method to call a private method.
apple.fruit_name("Apple") #fruit_You are passing an argument to the name method.
apple.info_fruit #info_You are calling the fruit method.
Output result
Apple
That is all.
We would appreciate it if you could point out any mistakes or lack of recognition.
Recommended Posts