Until now, I have not clearly understood the important concepts of Ruby, such as instances and classes, so I will explain them with examples. I think it's something you absolutely must know to use Ruby, but it wasn't easy to understand.
・ For those who are new to Ruby ・ People whose classes and instances are ambiguous
As an example, let's assume that users are posting with ids 1 to 3 as shown below under the Tweet class in a service like twitter.
At this time, each post enclosed in a black square is a ** instance **. Instances are said to be objects created from the types of classes. And Tweet is ** class **. An image of an instance belonging to a class. It's an important concept in Ruby! !!
class Tweet
#Class method
def self.tweet
puts "tweet"
end
#Instance method
def post_tweet(user,about)
puts "#{user}Is#{about}Posted about"
end
end
#Run
Tweet.tweet
new_tweet = Tweet.new()
new_tweet.post_tweet("choco","programming")
After execution
tweet
choco posted about programming
-Call with "class name.method" outside class. (Tweet.tweet in the above example) ・ If you cut yourself, you will get angry. (** declare itself as a class method **) => It can be defined by ** self. method name ~~ end ** in the class. -All, new, etc. are predefined class methods, and you can operate on the class. (All gets all instances of the class, new creates a new instance in the class)
-Call with "instance name.method" outside the class. (In the above example, new_tweet.post_tweet) Since the instance belongs to the class, create an instance with ** class name.new ** and execute the method for that instance. -Basically, I feel that instance methods are often used during implementation.
As I wrote this article, I thought that Ruby was a very easy-to-understand and intuitive design. From now on, I will try to define the method with a strong awareness of the instance class.
Thank you to everyone who read it. If you have any suggestions, please do not hesitate to contact us.