・ 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.
・ 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]"
・ 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 **
-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
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)
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
>> puts prefecture + "\t" + city
hokkaido sapporo
=> nil
>> puts prefecture + '\t' + city
hokkaido\tsapporo
=> nil
>> s = "racecar"
=> "racecar"
>> s.length
=> 7
>> s.reverse
=> "racecar"
>> s == s.reverse
=> true
>> 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
>> def palindrome_tester(s)
>> if s == s.reverse
>> puts "It's a palindrome!"
>> else
>> puts "It's not a palindrome."
>> end
>> end
=> :palindrome_tester
>> palindrome_tester("racecar")
It's a palindrome!
=> nil
>> palindrome_tester("onomatopoeia")
It's not a palindrome.
=> nil
>> palindrome_tester("racecar").nil?
It's a palindrome!
=> true
>> 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"
>> palindrome_tester(s.split(' ').join.downcase)
It's a palindrome!
=> nil
>> 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"
>> (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"
>> def random_subdomain
>> ("a".."z").to_a.shuffle[0..7].join
>> end
=> :random_subdomain
>> random_subdomain
=> "unwdemsp"
>> def string_shuffle(s)
>> s.split('').shuffle.join
>> end
=> :string_shuffle
>> string_shuffle("foobar")
=> "arbfoo"
>> 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}
>> 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
>> 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
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.
>> 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"
$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
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
>> 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
-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
・ 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