(Giri) A local government employee in his twenties works on a Rails tutorial [Chapter 4]

Premise

・ Rails tutorial is the 4th edition ・ This study is the 3rd lap (2nd lap after Chapter 9) ・ The author is a beginner who has done all of Progate.

Basic policy

・ If you read it, you will not understand it. ・ Search and summarize terms that you do not understand (at the bottom of the article, glossary). ・ Dive into what you do not understand. ・ Work on all exercises. ・ Do not copy chords as much as possible.

This is Chapter 4. I remember that this chapter was redundant. I will do it without saying anything. Click here for today's BGM. matryoshka "zatracenie[full album]"

[4.1.2 Custom helper memo]

・ Newly created method = custom helper ・ ** Helper used on all pages: Installed in app / helpers / application_helper.rb ** ・ ** Helper used only by a specific controller: Installed in app / helpers / (corresponding controller name) .rb **

[4.2.2 Character string memo and exercise]

-The puts method returns nil as the return value. The newline character \ n is added to the end of the output. -The print method does not add a newline character. -Expressions cannot be expanded in single quotes. Useful when you want to keep the entered characters as they are without escaping them

  1. Substitute the appropriate city / ward / town / village in the city variable and the appropriate prefecture in the prefecture variable. → city = "sapporo" prefecture = "hokkaido" (because I'm watching the game at Consadole Sapporo now)

  2. Let's create a character string of an address like "Shinjuku-ku, Tokyo" using the variables and formula expansion created earlier. Use puts for output. → Below

>> puts prefecture +  " " + city          
hokkaido sapporo
=> nil
  1. Try replacing the half-width space between the above character strings with a tab. (Hint: Same as newline character, tab is also special character) → Below
>> puts prefecture +  "\t" + city         
hokkaido        sapporo
=> nil
  1. What happens if you replace the character string replaced with a tab from double quotes to single quotes? → Below
>> puts prefecture +  '\t' + city         
hokkaido\tsapporo
=> nil

[4.2.3 Object and message delivery exercise]

  1. What is the length of the "racecar" string? Use the length method to find out. → Below
>> s = "racecar"
=> "racecar"
>> s.length
=> 7
  1. Use the reverse method to find out what happens when you read the "racecar" string in reverse. → Below
>> s.reverse
=> "racecar"
  1. Substitute "racecar" for the variable s. Then use the comparison operator (==) to see if the values of the variables s and s.reverse are the same. → I've already put it in. following
>> s == s.reverse
=> true
  1. What is the result of running Listing 4.9? What happens if I assign the string "onomatopoeia" to the variable s? Hint: Previously used command using the up arrow (or Ctrl-P command) Reusing is convenient because you don't have to type all the commands from scratch. ) → Below
>> puts "It's a palindrome!" if s == s.reverse
It's a palindrome!
=> nil
>> s = "onomatopoeia"
=> "onomatopoeia"
>> puts "It's a palindrome!" if s == s.reverse
=> nil

[4.2.4 Method definition exercise]

  1. Replace the FILL_IN part in Listing 4.10 with the appropriate code and define a method to check if it is a palindrome. Tip: See the comparison method in Listing 4.9. → Below
>> def palindrome_tester(s)
>>   if s == s.reverse
>>     puts "It's a palindrome!"
>>   else
>>     puts "It's not a palindrome."
>>   end
>> end
=> :palindrome_tester
  1. Use the method defined above to see if “racecar” and “onomatopoeia” are palindromes. If the result is that the first is a palindrome and the second is not a palindrome, it is a success. → Below
>> palindrome_tester("racecar")
It's a palindrome!
=> nil
>> palindrome_tester("onomatopoeia")
It's not a palindrome.
=> nil
  1. Call the nil? method on palindrome_tester ("racecar") and check if the return value is nil (that is, make sure the result of calling nil? Is true). .. This method chain means that the nil? method receives the return value in Listing 4.10 and returns the result. → Below
>> palindrome_tester("racecar").nil?
It's a palindrome!
=> true

[4.3.1 Array and range operator exercise]

  1. Divide the character string "A man, a plan, a canal, Panama" by "," to make an array, and assign it to the variable a. → Below
>> a = "A man, a plan, a canal, Panama".split(',')
=> ["A man", " a plan", " a canal", " Panama"]

2. Next, try substituting the result (character string) of concatenating the elements of variable a into variable s. → Below

>> s = a.join
=> "A man a plan a canal Panama"
  1. Divide the variable s with a half-width space, and then concatenate it again to make a character string (hint: You can do it on one line by using the method chain). Use the method to check the palindrome used in Listing 4.10 to make sure that the variable s is not a palindrome (currently yet). Use the downcase method to make sure s.downcase is a palindrome. → In a lump, it looks like this (I dropped the console once, so it was troublesome to redefine the method!)
>> palindrome_tester(s.split(' ').join.downcase)
It's a palindrome!
=> nil
  1. Create a range object from a to z and try to extract the 7th element. In the same way, try to extract the 7th element from the back. (Hint: don't forget to convert the range object to an array) → It's 6 because it starts from 0 at first.
>> A = ("a".."z").to_a
=> ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]
>> A[6]
=> "g"
>> A[-7]
=> "t"

[4.3.2 Block exercise]

  1. Use the range object 0.16 to output the square of each element. → Below
>> (0..16).each { |i| puts i**2 }
0
1
4
9
16
25
36
49
64
81
100
121
144
169
196
225
256
=> 0..16

2. Define a method called yeller (scream out loud). This method takes an array of string elements, concatenates each element, then capitalizes it and returns the result. For example, when you execute yeller (['o','l','d']), it is successful if the result "OLD" is returned. Tip: Try using the map, upcase, and join methods. → Below. I wonder if this is a smarter way. For example, you can just put a character string in the argument instead of an array.

>> def yeller(s)
>>   s.map(&:upcase).join
>> end
=> :yeller
>> yeller(['o','l','d'])
=> "OLD"
  1. Define a method called random_subdomain. This method generates 8 random characters and returns them as a string. Tip: This is a methodized version of the Ruby code used to create the subdomain. → Below
>> def random_subdomain
>>   ("a".."z").to_a.shuffle[0..7].join
>> end
=> :random_subdomain
>> random_subdomain
=> "unwdemsp"
  1. Replace the "?" Part in Listing 4.12 with the appropriate method. Tip: You can combine the split, shuffle, and join methods to shuffle the string (argument) passed to the method. → Below
>> def string_shuffle(s)
>>   s.split('').shuffle.join
>> end
=> :string_shuffle
>> string_shuffle("foobar")
=> "arbfoo"

[4.3.3 Hash and symbol exercises]

  1. Create a hash with the keys'one','two', and'three'and the respective values'uno','dos', and'tres'. Then look at each element of the hash and try to output each key and value in the form "'# {key}' Spanish is'# {value}'". → Below
>> n = { one: 'uno', two: 'dos', three: 'tres' }
=> {:one=>"uno", :two=>"dos", :three=>"tres"}
>> n.each do |key, value|                 
?>   puts "#{key}Spanish is#{value}"
>> end
one Spanish is uno
two Spanish is dos
three Spanish is tres
=> {:one=>"uno", :two=>"dos", :three=>"tres"}

2. Create three hashes, person1, person2, and person3, add the: first and: last keys to each hash, and enter an appropriate value (name, etc.). Then try creating a hash called params like this: 1.) Assign person1 to the value of key params [: father], 2). Assign person2 to the value of key params [: mother], 3). Assign person3 to the value of key params [: child]. Finally, check the hash of the hash to see if it's the correct value. (For example, make sure that params [: father] [: first] matches person1 [: first]) → Below. You are a Gamba supporter who understands the meaning of each name and key. (From the starting lineup in Section 14 of the 2020 season)

>> person1 = { first: "Yuki", last: "Yamamoto" }                                    
=> {:first=>"Yuki", :last=>"Yamamoto"}
>> person2 = { first: "Yosuke", last: "Ideguchi" }
=> {:first=>"Yosuke", :last=>"Ideguchi"}
>> person3 = { first: "Shu", last: "Kurata" }
=> {:first=>"Shu", :last=>"Kurata"}
>> params = { anchor: person1, rih: person2, lih: person3 }
=> {:anchor=>{:first=>"Yuki", :last=>"Yamamoto"}, :rih=>{:first=>"Yosuke", :last=>"Ideguchi"}, :lih=>{:first=>"Shu", :last=>"Kurata"}}
>> params[:anchor][:first] == person1[:first]
=> true

3. Try defining a hash called user. This hash has three keys: name,: email, and: password_digest, each value of which is assigned your name, your email address, and a random 16-character string. → Below

>> user = { name: "tk", email: "[email protected]", password_digest: ("a".."z").to_a.shuffle[0..15].join }
=> {:name=>"tk", :email=>"[email protected]", :password_digest=>"socxlgerjatyinbw"}

4. Use the Ruby API to find out about the merge method of the Hash class. Can you guess what the result will be without running the following code? If you can guess, run the code and see if the guess was correct.

{ "a" => 100, "b" => 200 }.merge({ "b" => 300 })

→ Honestly, even if you search by Rurima Search I don't really understand. Japanese is not Japanese. So, if you normally rely on Google Sensei, the merge method is a method that combines multiple hashes. Then, the merge "before" hash is combined with the merge "after" hash, but if there are duplicate hashes, the "after" hash is overwritten. So the above result should be b as 300. The actual results are below. It fits.

>> { "a" => 100, "b" => 200 }.merge({ "b" => 300 })
=> {"a"=>100, "b"=>300}

[4.4.1 Constructor exercise]

  1. What was the literal constructor that creates a range of objects from 1 to 10? (Review) → Below
>> r = 1..10
=> 1..10

2. Now use the Range class and the new method to create a range object from 1 to 10. Tip: You need to pass two arguments to the new method. → Below

>> r2 = Range.new(1,10)
=> 1..10

3. Use the comparison operator == to check that the objects created in the above two tasks are the same. → Below

>> r == r2
=> true

[4.4.2 Class inheritance exercise]

  1. Check the inheritance hierarchy of the Range class. In the same way, check the inheritance hierarchy of the Hash and Symbol classes. → First from Range.
>> r = Range.new(1,3)
=> 1..3
>> r.class
=> Range
>> r.class.superclass
=> Object
>> r.class.superclass.superclass
=> BasicObject
>> r.class.superclass.superclass.superclass
=> nil

Then Hash

>> h = {}
=> {}
>> h.class
=> Hash
>> h.class.superclass
=> Object
>> h.class.superclass.superclass
=> BasicObject
>> h.class.superclass.superclass.superclass
=> nil

Finally Symbol

>> s = :symbol
=> :symbol
>> s.class
=> Symbol
>> s.class.superclass
=> Object
>> s.class.superclass.superclass
=> BasicObject
>> s.class.superclass.superclass.superclass
=> nil

2. Omit self.reverse in Listing 4.15 and write reverse to see if it works. → Below

>> class Word < String
>>   def palindrome?
>>     self == reverse
>>   end
>> end
=> :palindrome?
>> s = Word.new("level")
=> "level"
>> s.palindrome?
=> true

[4.4.3 Exercise to change built-in class]

  1. Use the palindrome? Method to check that "racecar" is a palindrome and "onomatopoeia" is not a palindrome. Is the South Indian word "Malayalam" a palindrome? Tip: Don't forget to lowercase the downcase method. → Let's follow the flow of the exercise in 4.4.2.
s = Word.new("racecar")
=> "racecar"
>> s.palindrome?
=> true
>> s = Word.new("onomatopoeia")
=> "onomatopoeia"
>> s.palindrome?
=> false
>> s.downcase.palindrome?
=> true

2. Refer to Listing 4.16 and try adding the shuffle method to the String class. Tip: Listing 4.12 is also helpful.

  1. Use the comparison operator == to check that the objects created in the above two tasks are the same. → Collectively below
>>   def shuffle
>>     self.split('').shuffle.join
>>   end
>> end
=> :shuffle
>> "foobar".shuffle
=> "fobaro"
>> class String
>>   def shuffle
>>     split('').shuffle.join
>>   end
>> end
=> :shuffle
>> "foobar".shuffle
=> "boroaf"

[4.4.4 Controller class exercise]

  1. Open the Rails console in the Toy application directory created in Chapter 2 and execute User.new to check that the user object can be created. → I'm erasing toy_app ... So I ran git clone. I've become smarter again. I was asked for a username and password, but I was able to do it by entering my Github account name and login password.
$git clone https of the corresponding remote repository

And when I tried to get into the main subject, I got various errors ... budle install --without production and rails db: migrate to solve. You have successfully created a user object.

>> user = User.new
=> #<User id: nil, name: nil, email: nil, created_at: nil, updated_at: nil>

2. Check the inheritance hierarchy of the generated user object class. → Below

>> user.class
=> User(id: integer, name: string, email: string, created_at: datetime, updated_at: datetime)
>> user.class.superclass
=> ApplicationRecord(abstract)
>> user.class.superclass.superclass
=> ActiveRecord::Base
>> user.class.superclass.superclass.superclass
=> Object
>> user.class.superclass.superclass.superclass.superclass
=> BasicObject
>> user.class.superclass.superclass.superclass.superclass.superclass
=> nil

[4.4.5 User class exercise]

  1. Modify the name attribute defined in the User class and divide it into the first_name attribute and the last_name attribute. Also, try defining a full_name method that returns a string such as "Michael Hartl" using those attributes. Finally, let's replace the name part of the formatted_email method with full_name (successful if the result is the same as the original result) → Below

example_user.rb


class User
  attr_accessor :first_name, :last_name, :email
  
  def initialize(attributes = {})
    @first_name = attributes[:first_name]
    @last_name = attributes[:last_name]
    @email = attributes[:email]
  end
  
  def full_name
    "#{@first_name} #{@last_name}"
  end
  
  def formatted_email
    "#{self.full_name} <#{@email}>"
  end
end

On the console

>> require './example_user'
=> true
user = User.new(first_name: "t" ,last_name: "k", email: "[email protected]")
=> #<User:0x00000000030715e0 @first_name="t", @last_name="k", @email="[email protected]">
>> user.formatted_email=> "t k <[email protected]>"

2. Let's define an alphabetical_name method that returns in a format such as "Hartl, Michael" (a character string in which the surname and first name are separated by a comma + a single-byte space). → Below

  def full_name
    "#{@first_name} #{@last_name}"
  end
  1. Compare the results of full_name.split and alphabetical_name.split (','). Reverse and see if they give the same result. → Since you have filled in Exercise 2 above, reload it on the console. The above input value is also too short, so re-enter it. (Yat-san's a is missing ...)
>> require './example_user'=> true
>> user = User.new(first_name: "Ysuhito", last_name: "Endo", email: "[email protected]")
=> #<User:0x0000000003059968 @first_name="Ysuhito", @last_name="Endo", @email="[email protected]">
>> user.full_name.split=> ["Ysuhito", "Endo"]
>> user.alphabetical_name.split(', ').reverse
=> ["Ysuhito", "Endo"]
>> user.full_name.split == user.alphabetical_name.split(', ').reverse
=> true

Chapter 4 Summary

-Use the helper definition file properly depending on whether it is used as a whole or on a specific controller. ・ Imprint object-oriented in your senses. Everything is an object. -Classes can be inherited. There is always an original class. Since it is inherited, various functions can be used. -Class methods are defined in classes, and instance methods are defined in instances. ・ () Or {} can be omitted. For example, {} in the last block of the argument. -: Name is a symbol. Hash notation is generally ~~: "mojiretu" is written. ・ Since there were some words I didn't understand, I have summarized them in a glossary.

This chapter was a lot of work. But knowledge of abbreviations may be important for code reading. From the next chapter 5, we will return to app development again!

Go to Chapter 5! Click here for Chapter 3 Click here for premise and author status for learning

A glossary that somehow captures the image

・ Built-in functions A function that is prepared in advance for specifications such as programming languages and can be used as standard. On the other hand, a function defined and implemented by a programmer in code is called a "user-defined function".

・ API (Application Programming Interface) A convention that defines the procedure and data format for calling and using the functions of a certain computer program (software) and the data to be managed from another external program. Using the API has the advantages of streamlining software development, improving security, and easily obtaining the latest information.

・ Escape (escape character / processing) A character (, etc.) that has the function of making a character string that has meaning into a simple character string and vice versa.

・ Literal Letters and numbers written in the source code.

・ Nest A state or structure in which something of the same shape and type (one size smaller) is contained in something.

・ Accessir In object-oriented programming, a method provided to access member variables (attributes, properties) inside an object from the outside. It is prepared to hide member variables inside the object and prevent them from being directly referenced from the outside.

・ Member variables An instance variable.

Recommended Posts

(Giri) A local government employee in his twenties works on a Rails tutorial [Chapter 11]
(Giri) A local government employee in his twenties works on a Rails tutorial [Chapter 14]
(Giri) A local government employee in his twenties works on a Rails tutorial [Chapter 12]
(Giri) A local government employee in his twenties works on a Rails tutorial [Chapter 5]
(Giri) A local government employee in his twenties works on a Rails tutorial [Chapter 3]
(Giri) A local government employee in his twenties works on a Rails tutorial [Chapter 4]
(Giri) A local government employee in his twenties works on a Rails tutorial [Chapter 8]
(Giri) A local government employee in his twenties works on a Rails tutorial [Chapter 6]
(Giri) A local government employee in his twenties works on a Rails tutorial [Chapter 13]
(Giri) A local government employee in his twenties works on a Rails tutorial [Chapter 9]
(Giri) A local government employee in his twenties works on a Rails tutorial [Chapter 10]
(Giri) A local government employee in his twenties works on a Rails tutorial [Chapter 7]
(Giri) A local government employee in his twenties works on a Rails tutorial [Chapter 2]
(Giri) A local government employee in his twenties works on a Rails tutorial [Introduction]
[Rails Tutorial Chapter 5] Create a layout
[Rails Struggle/Rails Tutorial] What you learned in Rails Tutorial Chapter 6
[Rails Struggle/Rails Tutorial] What you learned in Rails Tutorial Chapter 3
(Ruby on Rails6) Creating data in a table
[Rails tutorial] A memorandum of "Chapter 11 Account Activation"
rails tutorial Chapter 6
rails tutorial Chapter 1
rails tutorial Chapter 7
rails tutorial Chapter 5
rails tutorial Chapter 10
rails tutorial Chapter 9
rails tutorial Chapter 8
[Rails Tutorial Chapter 2] What to do when you make a mistake in the column name
Rails Tutorial Chapter 5 Notes
Rails Tutorial Chapter 10 Notes
Rails Tutorial Chapter 3 Notes
Rails Tutorial Chapter 3 Learning
Rails Tutorial Memorandum (Chapter 3, 3.1)
Rails Tutorial Chapter 4 Notes
Rails Tutorial Chapter 4 Learning
Rails Tutorial Chapter 1 Learning
Rails Tutorial Chapter 2 Learning
Rails Tutorial Chapter 8 Notes
Rails Tutorial Memorandum (Chapter 3, 3.3.2)
Difficulties in building a Ruby on Rails environment (Windows 10) (SQLite3)
How to display a graph in Ruby on Rails (LazyHighChart)
Apply CSS to a specific View in Ruby on Rails