Currently, I am studying to get the Ruby engineer certification exam silver. I still have a lot of understanding of the language, so I will output from the basics.
Here's how to generate a normal array
mr_children = ["GIFT", "himawari", "simple"] #Store elements in square brackets
p mr_children
=> ["GIFT", "himawari", "simple"]
When using the% notation, commas and quotation marks disappear and it is a little refreshing.
mr_children = %w(GIFT himawari simple)
p mr_children
=> ["GIFT", "himawari", "simple"]
mr_children = %w(GIFT himawari simple)
mr_children << "over" #Add element to the very end of the array
p mr_children
=> ["GIFT", "himawari", "simple", "over"]
mr_children.insert(1, "Esora") #Specify the subscript in the first argument and insert the element there
p mr_children
=> ["GIFT", "Esora", "himawari", "simple", "over"]
mr_children = %w(GIFT himawari simple)
p mr_children * 3 #When multiplied by a numerical value
=> ["GIFT", "himawari", "simple","GIFT", "himawari", "simple","GIFT", "himawari", "simple"]
mr_children = %w(GIFT himawari simple)
p mr_children * ";" #When multiplied by a character string
=> "GIFT;himawari;simple"
#A string that concatenates the elements with the specified string in between is returned.
s = "To be or not to be, that is the question." #Define a string in the variable s
hash = Hash.new(0) #Create an instance of Hash class (empty inside)
s.scan(/\w+/) {|i| hash[i] += 1}
#Get the matched string as an array. Pass the value of the array to the block variable i and define it as a hash key. Add the number 1 to the corresponding value.
p hash
=> {"To"=>1, "be"=>2, "or"=>1, "not"=>1, "to"=>1, "that"=>1, "is"=>1, "the"=>1, "question"=>1}
#The number of occurrences for each word was calculated.
This → / \ w + / memo \ w => Alphanumeric, underscore
The scan method returns an array of strings that match the regular expression. What it looks like before it is stored in the hash key
s = "To be or not to be, that is the question."
p s.scan(/\w+/)
=> ["To", "be", "or", "not", "to", "be", "that", "is", "the", "question"]
A state like sashimi carved by words.
To_Be_Continued...
Recommended Posts