I tried to collect and solve Ruby's "class" related problems.

I don't know the Ruby class

I thought I'd read the Cherry book and output it, but when it comes to creating my own program, it's difficult to solve. .. ..

I have collected ** basic problems ** for those who have the same problems as me.

Even if it is a basic problem, honestly, if you solve this problem with ambiguous knowledge, you may not understand it.

If possible, I think it is better to proceed without looking at the answer, but if you do not understand by all means, I will write the answer at the bottom of the article so please refer to it.

And since I myself said that I couldn't understand even after reading the answer, I will describe the points that I did not understand.

Problem (3 questions)

① About class variables and class methods

sample.rb


class Car
  def self.run
    @@count += 1
  end

  def count
    @@count
  end
end

car1 = Car.new
car1.run

car2 = Car.new

car2.run
car1.run

puts Car.count

I referred to Problem of this article.

When I run the above program, I get an error. Please correct some parts and change the source so that the output is as expected.

(Expected output) -Calling the instance method run increments the class shared counter by 1. -Calling the class method `count` returns the current counter value.

If 3 is displayed, it's okay.

The following articles have been very helpful in solving this problem. https://qiita.com/mogulla3/items/cd4d6e188c34c6819709

② Singular method

I have quoted this article.

food.rb


class Food
  def eat
    puts "I like."
  end
end
 
natto = Food.new()
wasabi = Food.new()
karaage = Food.new()

natto.eat #=>I like.
wasabi.eat #=>I don't like.
karaage.eat #=>I love.

Change the code so that the output is as commented out.

③ Define a Rap class that inherits the Music class

I referred to this article.

Predict the code to be written in the Rap class from the output result below.

sample.rb


class Music
  def mc
    puts "This is #{@genre} of #{self.class.to_s}"
  end
 
  def initialize(genre)
    @genre = genre
  end
end

Rap.new("mc-battle").mc

(Output example)

This is mc-battle of Rap
Yo, mic check 1, 2.

-* * * * * * * * * * * Answer * * * * * * * * * * *-

① About class variables and class methods

You can't solve it unless you understand how to use class variables and class methods.

--Classes and their instances are scoped --Similar to constants, but different in that class variables can be changed as many times as you like --Accessible within class methods, instance methods, and class definition expressions

The following articles were helpful and very helpful in solving this problem. https://qiita.com/mogulla3/items/cd4d6e188c34c6819709

First, the points to look at are ** 2, 6 lines **.

sample.rb


class Car
  def self.run #2nd line
    @@count += 1
  end

  def count #6th line
    @@count
  end
end

car1 = Car.new
car1.run

car2 = Car.new

car2.run
car1.run

puts Car.count

Didn't you notice?

Look at the last line.

puts Car.count



 This seems to be overhanging the Car class count method, isn't it strange?

 When calling the class as it is, the class method must be issued.

 If you fix it


#### **`sample.rb`**
```rb

class Car
  def self.run #2nd line
    @@count += 1
  end

  def self.count #6th line
    @@count
  end
end

#-Omission-

puts Car.count #Last line

And the second line is also strange.

This must be an instance method.

sample.rb


class Car
  def run #2nd line/def self.Change from run
    @@count += 1
  end
end

car1 = Car.new
car1.run

Because, in the class, an instance is created with `` `car1```, so it must be an instance method as a method to call that instance.

But that's not the end.

** The class variable @@ count is not defined. ** **

sample.rb


class Car
  @@count = 0 #Definition of class variables

  def run #Class method
    @@count += 1 #@@count is a class variable
  end

  def self.count #Instance method
    @@count
  end
end

car1 = Car.new
car1.run

car2 = Car.new

car2.run
car1.run

puts Car.count

# => $ ruby sample.rb 
# => 3

This is okay.

② Singular method

What is a singular method in the first place? ** Refers to a method specific to one instance. ** **

Singular methods can be defined with ``` def object name. Method name` ``. https://qiita.com/k-penguin-sato/items/d637dced7af32e4ec7c0

Therefore,

food.rb


class Food
  def eat
    puts "I like."
  end
end
 
natto = Food.new()
wasabi = Food.new()
karaage = Food.new()

#--add to--↓

def wasabi.eat
  puts "I don't like."
end

def karaage.eat
  puts "I love."
end

#--add to--↑

natto.eat
wasabi.eat
karaage.eat

Define methods with the same name but different behaviors for objects that are instances of the same class.

This is a singular method, which is not for the class, but for the instance made from the class.

Therefore, you can output from each method.

(result)

I like.
I don't like.
I love.

③ Define a Rap class that inherits the Music class

sample.rb


class Music
  def mc
    puts "This is #{@genre} of #{self.class.to_s}"
  end

  def initialize(genre)
    @genre = genre
  end
end

Rap.new("mc-battle").mc

- Self.class.to_s: Converts the class name of the instance itself created like `` `Rap.new``` to a character string.

Now, let's create `Rap class`.

sample.rb


#--Omission--
class Rap < Music
end

Look at the output characters.

Yo, mic check 1, 2.



 Since it is an output that is not defined in the Music class, we will output it in the Rap class.

 If you look at ``` Rap.new ("mc-battle "). Mc``` on the last line, the method uses ``` mc```, so I will describe it.


#### **`sample.rb`**
```rb

#--Omission--
class Rap < Music
  def mc
  end
end

Since it inherits the Music class, if you describe the necessary part

sample.rb


#--Omission--
class Rap < Music
  def mc
    puts "Yo, mic check 1, 2."
  end
end

But this is not the end.

We haven't been able to call the Music class yet.

What should i do?

** Execute the "super" method. ** **

The super method * finds and executes a method in the superclass that has the same method name as the called method. ** **

Then, if you rewrite

sample.rb


class Music
  def mc
    puts "This is #{@genre} of #{self.class.to_s}"
  end
 
  def initialize(genre)
    @genre = genre
  end
end

class Rap < Music
  def mc
    super #Additional code
    puts "Yo, mic check 1, 2."
  end
end

Rap.new("mc-battle").mc

done.

Recommended Posts

I tried to collect and solve Ruby's "class" related problems.
I tried to solve AOJ's Binary Search
I tried to implement polymorphic related in Nogizaka.
I tried to link grafana and postgres [docker-compose]
I tried to link JavaFX and Spring Framework.
[Java] I tried to solve Paiza's B rank problem
I started MySQL 5.7 with docker-compose and tried to connect
I tried to integrate AWS I oT button and Slack
I tried to solve AOJ's Small, Large, or Equal
I tried to chew C # (reading and writing files)
I tried to summarize the basics of kotlin and java
I tried to verify this and that of Spring @ Transactional
I tried to make Java Optional and guard clause coexist
I tried to summarize personally useful apps and development tools (development tools)
I tried to summarize personally useful apps and development tools (Apps)
I tried to verify yum-cron
[Rails] I tried to implement "Like function" using rails and js
I tried to express the result of before and after of Date class with a number line
I tried to solve the problem of "multi-stage selection" with Ruby
I tried to integrate Docker and Maven / Netbean nicely using Jib
[Tips] How to solve problems with XCode and Swift for beginners
I tried to see if Koalas and Elasticsearch can work together
I tried to summarize the methods of Java String and StringBuilder
I tried to solve the paiza campaign problem "Challenge from Kaito 813"
I tested how to use Ruby's test / unit and rock-paper-scissors code.
I tried to solve the problem of Google Tech Dev Guide
I tried to chew C # (indexer)
I tried to summarize iOS 14 support
I tried to interact with Java
I tried to explain the method
I tried to summarize Java learning (1)
I tried to understand nil guard
I tried to summarize Java 8 now
I tried to chew C # (polymorphism: polymorphism)
I compared Java and Ruby's FizzBuzz.
I tried to explain Active Hash
I tried to make a parent class of a value object in Ruby
I tried to summarize the key points of gRPC design and development
I tried to make my own transfer guide using OpenTripPlanner and GTFS
I made a virtual currency arbitrage bot and tried to make money
I tried to solve the tribonacci sequence problem in Ruby, with recursion.
I introduced OpenAPI (Swagger) to Spring Boot (gradle) and tried various settings
I tried to measure and compare the speed of GraalVM with JMH
I tried to summarize the methods used
I tried to introduce CircleCI 2.0 to Rails app
I tried migrating Processing to VS Code
I tried to summarize Java lambda expressions
I tried to get started with WebAssembly
Java implementation to create and solve mazes
I tried to implement the Iterator pattern
I tried to summarize the Stream API
I tried to build AdoptOpenjdk 11 on CentOS 7
What is Docker? I tried to summarize
I tried to build Ruby 3.0.0 from source
I tried to use Selenium like JQuery
I tried to touch JavaScript Part.2 Object-oriented
I tried to implement ModanShogi with Kinx
A story when I tried to make a video by linking Processing and Resolume
I tried to solve the tribonatch sequence problem in Ruby (time limit 10 minutes)
I tried to verify whether it would be fun to combine "programming" and "hobbies".
I tried to automatically generate a class to convert from a data class to a Bundle with APT