This is a memo for learning content output and self-reflection by beginners introductory to Ruby basic grammar. The value is mostly yakiniku for fun notes.
** References ** Progate Ruby Learning Course Introduction to Dot Installation Ruby
--"": Special characters and expression expansion can be used --"'": The value is output as it is --"\ n": Line break --"\ t": Show tab -"* Numerical value": Display the number of numerical values
learning.rb
price.upcase #Returns a string in uppercase
price.upcase! #Rewrite the original string to uppercase while returning the string in uppercase
price.reberse #Returns the string in reverse order
price.emyty? #Check if the string is empty
price.include?("t") #Find out if a particular character is included
learning.rb
p 10 + 3 # 13
p 10 * 3 # 30
p 2.4 * 2 # 4.8
p 10 / 3 # 3
p 10.0 / 3 # 3.33333...(Show after the decimal point)
p 10 % 3 # 1
p Rational(2, 5) + Rational(3, 4) #(Fraction 23/20)
p 2/5r + 3/4r #(Abbreviation for fractional Rational)
p 52.6.round #Rounding
p 52.6.floor #Truncate after the decimal point
p 52.6.ceil #Round up after the decimal point
--If you write "#" at the beginning of a line, that line becomes a comment. -All lines enclosed by = begin ~ = end are comments
learning.rb
#I haven't eaten yakiniku, so I don't understand much from the instance variables.
=begin
So calmly organize the information and refer to other articles
Deepen your understanding or eat yakiniku ry
=end
"P" is displayed surrounded by double quotation marks In the case of a complicated structure, this will be displayed as a character string so that it is easy to understand.
learning.rb
print "Do you like Yakiniku?" #Output without line breaks
puts "Do you like Yakiniku?" #Output with line breaks
p "Do you like Yakiniku?" #For debugging
learning.rb
p 29 + "29".to_i #Convert to integer "too integer" to_i
p 29 + "29".to_f #Convert to floating point number "to float" to_f
p 29.to_s + "29" #Return to string "String" to_s
learning.rb
# t_a (to Array)Convert hash to array
# to_ #h(to Hash)Convert array to hash
price = {Upper tongue: 1800,Upper skirt steak: 1500}
p price.to_a.to_h
learning.rb
puts %Q(hello) #""Represent the character string enclosed in
puts %(hello) #The above Q can be omitted
puts %q(hello) #''Represent the character string enclosed in
If you want to use "'in" "" or "''" It is necessary to add "" to mean that it is not a delimiter % Notation is not required and may be easier to read
learning.rb
puts "he\"llo" puts %(hello)
puts 'he\'llo' puts %q(hello)
If you write a lot of values, you can also write like this
learning.rb
p ["red", "blue"] p %W(red blue)
p ['red', 'blue'] p %w(red blue)
** "string"% value ** Display various values with formatting
--% s: string --% d: Integer --% f: Floating point number
learning.rb
p "name: %s" % "Aged ribs"
p "name: %10s" % "Aged ribs" #Secure a width of 10 digits
p "name: %-10" % "Aged ribs" #Secure 10 digits + left justified
learning.rb
p "id: %05d, rate: %10.2f" % [29, 2,929]
#If there are multiple values, pass them as an array
#If id is an integer and rate is a floating point number
#I want the id to be 5 digits, but if it is less than 5 digits, fill it with 0
#The rate has 10 digits before the decimal point and 2 digits after the decimal point.
printf/Sprintf printf Instructions for displaying a formatted string
learning.rb
printf("name: %10s\n", "taguchi")
printf("id: %05d, rate: %10.2f\n", 355, 3.284)
Sprintf A command that returns a string instead of displaying it Since the character string is returned, display it with p
learning.rb
p sprintf("name: %10s\n", "taguchi")
p sprintf("id: %05d, rate: %10.2f\n", 355, 3.284)
learning.rb
colors = ["red", "blue", "yellow"]
p colors[0] #Subscript(Start from 0)Output
p colors[-1] #Outputs the subscript (1 at the end) counted from the end
p colors[0..2] #Output 0 to 2
p colors[0...2] #Output 0 to 1 (until just before 2)
p colors[5] #nil (nothing)
colors[0] = "pink" #Change the value of the specified subscript
colors[1..2] = ["white", "black"] #Change the specified numbers at once
colors.push("gold") #Add value to the end
colors << "silver" #Abbreviation to add a value at the end
learning.rb
p colors.size #Indicates the number of elements
p colors.sort #Sorts the elements
How to manage multiple values at once by pairing keys and values (object)
** Array **: Manage multiple values side by side ** Hash **: Manage each value with a name called a key
Arrays enclose elements in [], but hashes in {} {Key 1 => Value 1, Key 2 => Value 2}
Connect the key and value with "=>" Like arrays, elements are separated by commas (,)
learning.rb
prices = {"bibimbap" => 800, "gukbap" => 700}
Objects like identifiers starting with: "Symbol object" is often used as the key It's faster than using strings and is often used in Ruby.
learning.rb
prices = {:bibimbap => 800, :gukbap => 700}
Hashes using the above symbols are often used, so there is a short notation.
learning.rb
prices = {bibimbap: 800, gukbap:700}
Access to each hash element is the same as an array
learning.rb
p prices[:bibimbap] #Use symbols
Update hash elements
learning.rb
prises[:bibimbap] = 900 #update
Add hash element Add element by writing hash [new key] = value Note that if you specify an existing key, it will be updated instead of adding an element.
learning.rb
prices[:Namul] = 650 #add to
learning.rb
p prices.size #Method that pulls the number of elements
p prices.keys #Method that pulls the list of keys
p prices.values #Method that pulls the list of values
p prices.has_key?(:gukbap) #A method to check if the key exists
learning.rb
price = gets.to_i #When converting to a number to_i
signal = gets.chomp
#gets reads one line but has a line feed code at the end
#Remove the last newline code with a method called chomp
if
learning.rb
if money > 15000
puts "You can buy yakiniku!"
elsif money > 7000
puts "Let's go yakiniku!"
else
puts "I want to eat yakiniku..."
end
If it is a simple conditional branch, if can be written after it.
learning.rb
puts "You can buy yakiniku!" if money > 15000
case Processing when you want to send out some message according to the value The following can be realized with if, but in some cases it can be written neatly using case
learning.rb
case meat
when "Calvi"
puts "Let's make the upper ribs!"
when "Loin", "Harami" #Can be separated by commas
puts "Let's put it on!"
when "Beef tongue salt"
puts "Only Tan won"
else
puts "Let's definitely order tongue!"
--while is a condition --times is the specified number --for (each) is the number of elements
while
learning.rb
i= 0 #Initialize i with 0
while i < 10 do #Repeat less than 10
puts "#{i}: I want to eat yakiniku"
i += 1
end
time Useful when the number of repetitions is fixed Write the process you want to do from do to end
learning.rb
10.times do |i|
puts "#{i}: I want to eat yakiniku"
end
#If you want to know how many loops you have, after do|variable|
If there is only one line between do and end, you can substitute {}
learning.rb
10.time { |i| puts "#{i}: hello" }
for For for some kind of collective object (array or hash) Also, only the number of elements of the object that represents the range Instructions that can repeat some processing
learning.rb
for i in 15..29 do #do is optional
p i
end
#Array
for meat in ["tongue", "offal"] do
p meat
end
#hash
for meat, price in {tongue:1000, offal:800} do
p "#{meat}: #{price}"
end
each Because for uses a method called each internally for can be rewritten using each
As with the time method, if the process to be repeated is about one line It is also possible to enclose do to end in {} and express it in one line
learning.rb
(15..29).each do |i|
p i
end
Array
["tongue", "offal"].each do |meat|
p meat
end
hash
{tongue:1000, offal:800}.each do |meat, price|
p "#{meat}: #{price}"
end
loop
learning.rb
i = 0
loop do
p i
i += 1
end
The process of looping forever is often used with instructions to exit the loop.
break
learning.rb
10.times do |i|
if i == 7
break #Exit the loop just before 7
end
p i
end
next
learning.rb
10.times do |i|
if i == 7
next #Skip 7 once
end
p i
end
break, next Can be used in iterative processing such as while, for, and times, including loops
A collection of multiple processes into one
If you don't use the method, you need to write the same process many times. It can be written simply by grouping common processes into methods.
learning.rb
#When not using the method
puts "Good evening"
puts "I'm Prince Calvi"
puts "Good evening"
puts "I am Mr. Tan"
puts "Good evening"
puts "I am Minister Harami"
#When using the method
def introduce(name)
puts "Hello"
puts "I#{name}is"
end
introduce("Prince Calvi")
introduce("Mr. Tan")
introduce("Minister Harami")
Write the process you want to put together between "def method name" and "end" This is called "defining a method" The figure on the right defines an introduce method that produces two outputs.
learning.rb
Format
def method name
processing
end
def introduce
puts "Hello"
puts "I'm yakiniku"
end
introduce #Call the introduce method
learning.rb
Format
def method name (argument name)
processing
end
Method name (value)#Method call+Value assigned to argument
learning.rb
def introduce(name)
puts "Good evening"
puts "I#{name}is" #Arguments can be used like variables in methods
end
introduce("Yakiniku brother")
Methods with arguments cannot be called without passing arguments Note that an error will occur
learning.rb
def meat(name, price) #From the left, the first argument and the second argument
puts "#{name}"
puts "#{price}Circle"
end
meat("Pork toro", 800)
You can use return in a method to receive the value at the caller By writing "return value", the method returns that value as the return value.
learning.rb
Format
def method name
return value#Returns a value to the caller (= return value)
end
def add(a,b)
return a + b #The sum of a and b is called as the return value
end
If there is a return value, the calling part of the method is replaced with the return value as it is By writing to assign the calling part of the sod to a variable You can receive the return value of the method.
learning.rb
def add(a,b)
return a + b
end
sum = add(1,3) #Call part
puts sum #Output 4
As for the return value, various values can be used as well as the argument.
If you return a conditional expression like the one used in the if statement, You can return the boolean value (true or false) obtained as a result of the conditional expression. Methods that return a boolean value have the convention of adding a "?" To the end of the method name.
learning.rb
def meat_free?(price)
return price >= 10000
end
if meat_free?(14000)
puts "Next time you visit the store, beef tongue salt service"
else
puts "Kimchi service the next time you visit"
end
return not only returns a return value, but also has the property of terminating the processing of the method. Therefore, the processing of the method after return is not executed.
learning.rb
def add(a, b)
return a + b #The process ends here
puts "Calculated" #Not executed
end
In the method, by combining conditional branching Multiple returns can be used
learning.rb
def price_with_shipping(price)
if price >= 10000
return price
end
return price + 500
end
puts "The total amount is 3000 yen"
puts "The payment amount includes take-out meat#{price_with_shipping(8000)}It's a yen"
#Output for 8500 yen
puts "The total price of the product is 10,000 yen"
puts "Payment amount includes shipping fee#{price_with_shipping(10000)}It's a yen"
#Output for 10,000 yen
As the number of arguments increases, it is difficult for the caller to know which argument the value goes into. By using keyword arguments, the caller can specify the arguments.
In addition to the usual method writing
learning.rb
#How to write so far
def introduce(name, age, food)
puts "I#{name}is"
puts "Age is#{nage}I'm old"
puts "What is your favorite food#{food}is"
end
introduce("Yakiniku brother", 37, "Grilled meat")
#It's hard to tell which argument each value goes into
#How to write using keyword arguments
def introduce(name:, age:, food:) #Add a colon
puts "I#{name}is"
puts "Age is#{nage}I'm old"
puts "What is your favorite food#{food}is"
end
introduce(name:"Yakiniku brother", age:37, food:"Grilled meat")
#How to write the argument name when calling
--Blueprint: Class --Things: Instance
The class is like a blueprint An instance that corresponds to the actual "thing" created from the blueprint "Instance variables" that are the information that the instance has The "instance method" to call for an instance is Define in class
STEP1 Prepare a class STEP2 Create an instance from the class STEP3 Add information to the instance
Class can be defined by "class class name" Class names must always start with "uppercase" + "end"
learning.rb
class Menu #Class names start with a capital letter
end #Don't forget end
attr_accessor To have information, use "attr_accessor symbol" An instance of the Menu class can have information called name Also, this information called "name" is called an "instance variable".
learning.rb
class Menu
attr_accessor :name
end
#An instance of the Menu class can have information called name
#This information called name is called an instance variable.
To create a new instance based on the class (blueprint) "class name.new" Also, the instance created by "variable name = class name.new" can be assigned to the variable.
To give information to the instance, prepare it in the class You need to assign a value to an instance variable Specifically, by setting "instance.variable name = value" You can set a value for that instance variable
learning.rb
class Menu
attr_accessor :name
attr_accessor :price
end
menu1 = Menu.new
menu1.name = "Chateaubriand" #Chateaubriandを代入
puts menu1.name #Output Chateaubriand
The method defined in the class is called as used for the instance. Specifically, by doing something like "instance.method name" That method can be called = instance method
learning.rb
class Menu
attr_accessor :name
attr_accessor :price
def show
puts "I'm meat"
end
end
menu1 = Menu.new
menu1.show #instance.Call by method name
Instance methods can also take arguments and return a return value
learning.rb
class Menu
|
def show(data) #argument
return "I#{data}is" #Return value
end
end
menu1 = Menu.new
puts menu1.show("Meat")
By using "self" in the instance method and setting it as "self.variable name" Can handle instance variables In the instance method, the variable "self" The called instance itself is assigned
learning.rb
class Menu
|
def show_name
puts "I#{self.name}is"
end
end
menu1 = Menu.new
menu1.name =Garlic
menu1.show_name #Instance method call
You can execute the process immediately after creating the instance. Called automatically immediately after creating an instance with "class name.new"
The initialize method can be defined like any other instance method The following is immediately after the Menu instance is created by "Menu.new" The initialize method is called and the processing in it is being executed
learning.rb
class Menu
|
def initialize
puts "Menu generated"
end
|
end
menu1 = Menu.new
# Menu.The initialize method is automatically called when new is executed
Because you can handle instance variables with "self.variable name" in the instance method You can assign a value to an instance variable with "self. variable name = value"
learning.rb
class Menu
|
def initialize
self.name = "Marucho"
end
|
end
menu1 = Menu.new
puts menu1.name
#Immediately after instantiation"Marucho"To the instance variable name
The initialize method can pass arguments like a normal instance method At that time, by passing an argument to "class.new" You can pass that value to the initialize method
learning.rb
class Menu
|
def initialize(message) #The meat is turned inside out only once, but it comes over
puts message
end
|
end
menu1 = Menu.new("Meat is turned inside out only once")
By assigning the argument value to the instance variable with the initialize method You can change the value of the instance variable for each instance At that time, you can write it easily by using keyword arguments
learning.rb
class Menu
|
def initialize(name:, price:)
self.name = name
self.price = price
end
|
end
menu1 = Menu.new(name: "Marucho", price: 800)
(Example at the time of division) After moving the definition of Menu class from index.rb to menu.rb Make the code in menu.rb available in index.rb By saying "require" ./menu "" in the top line of index.rb You will be able to read the code in menu.rb
learning.rb
# index.rb
require "./menu"
menu1 = Menu.new(name: "hearts",・ ・ ・)
|
Instance created from Menu class can also be an element of array Assign an array with each instance as an element to the variable menus The following is a case where each menu is displayed by using the each statement for the array.
learning.rb
# index.rb
menu1 = Menu.new(name: "hearts", price: 900)
menu2 = Menu.new(name: "lever", price: 800)
|
menus = [menu1, menu2, ....]
menus.each do |menu| #Display menus one by one using each statement
puts menu.info
end
Creating a new class based on a certain class is called "inheritance". By setting "class new class name <original class name" You can define a new class by inheriting another class The new class is "child class" The original class is the "parent class"
learning.rb
require "./menu"
class Food < Menu
end
The child class inherits the instance variables and instance methods of the parent class An instance of the Food class is as shown in the example below. You can call instance variables and instance methods of Menu class
learning.rb
# index.rb
food1 = Food.new(name: "Akasen", price: 900)
puts food1.name
puts food1.info
# menu.rb
class Menu
attr_accessor :name
|
def info
return "#{self.name} #{self.price}Circle"
end
end
Use "attr_accessor" as usual to add an instance variable to a child class The Food class below inherits from the Menu class ・ Name ・ price ・ calorie 3 instance variables can be used
learning.rb
# index.rb
food1 = Food.new(name: "Akasen", price: 900)
puts food1.name
puts food1.info
# menu.rb
class Menu
attr_accessor :name
attr_accessor :price
|
end
# food.rb
class Food < Menu
attr_accessor :calorie #Added "calorie" to Food class
end
If you define a method with the same name as the method in the parent class in the child class Method can be overridden = "override" When overridden, the child class instance is not a parent class method Call the method defined in the child class
** (Override mechanism) ** An instance of a child class preferentially calls a method defined in the child class. Therefore, if the child and parent classes have methods with the same name Since the method of the child class is called, the content of the method will be overwritten as a result.
super By setting "super" in the overridden method, You can call a method with the same name in the parent class Since we are calling the method to the last Arguments need to be passed to super according to the method definition of the parent class
learning.rb
# menu.rb
class Menu
attr_accessor :name
attr_accessor :price
def initialize(name:, price:)
self.name = name
self.price = price
end
|
end
# food.rb
class Food < Menu
attr_accessor :calorie
def initialize(name:, price:, calorie:)
super(name: name, price: price) #Call the method of the same name in the parent class
self.calorie = calorie
end
|
end
Date class = Class that handles dates Date class is a class already prepared by Ruby By loading with require, you can use it without having to define the class yourself.
(Note that the required classes are slightly different for the already prepared classes.)
learning.rb
require "date"
# "./date"Note that it is not
The Date class is the same as the classes we have dealt with so far You can create an instance by setting Date.new When you puts an instance of the Date class You can display the date as below
learning.rb
reequire "date"
date1 = Date.new(2020,12,18) #Create a Date instance by passing "date" as an argument
puts date1
#Output 2014-07-31
In the Date class, by setting Date.today, You can create an instance of today's date
learning.rb
require "date"
date1 = Date.today
puts date1
Class method can be defined by "def class name.method name" The difference from the instance method is that the class name must be written before the method name.
The following defines a class method called "is_discount_day?" In the Menu class.
Class methods are just as defined It can be called by setting "class name.method name"
learning.rb
Definition
def class name.Method name
#processing
end
Example
class Menu
|
def Menu.is_discount_day?
#processing
end
end
puts Menu.is_discount_day?
The method to call for the instance is "instance method" The method to call for the class is "class method"
learning.rb
class Menu
|
def info #Instance method definition
end
end
menu1 = Menu.new
menu1.info #Instance method calls to instance
learning.rb
class Menu
def Menu.is_discount_day? #Class method definition
end
end
Menu.is_discount_day? #Class methods call on the class
Recommended Posts