What impressed me as a beginner in writing Ruby

While creating a portfolio in Ruby Impressed when going back and forth with the basics of Ruby I will summarize how to write Ruby and the rules.

Update from time to time for yourself.

Write variables in snake case
special_price = 200
When using expression expansion, "" double quotes
puts "#{special_price}"
When using single (double) quotes in a string
puts "\"Hello\""
#=> "Hello"
The number _ is ignored
1_000_000_000
#=> 1000000000
For division between integers, the solution is also an integer
1 / 2 #=>0
1.0 / 2 #=>0.5
++ is syntactically invalid
n += 1 #=>2
n *= 3 #=>6
n /= 2 #=>3
n **= 2 #=>9
Rational number
0.1 * 3.0 == 0.3 #=>false
0.1 * 3.0 <= 0.3 #=>false
3/10 instead of decimal with Rational class
0.1r * 3.0r #=>(3/10)
&&Is||More priority

The if statement returns the last evaluated expression
greeting =
    if
        
    elsif
        
    else
        
    end
You can single line your code with if then
if (processing) then (Return value)
%notation
%q!! #=> ' '
%Q!! #=> " "
%!! #=> " "
Here document
a = <<TEXT
String
TEXT
Format string
'%0.3f' % 1.2 #=>"1.200"
Exponential notation
2e-3 #=> 0.002
#2×10^-3
Conditional operator (ternary operator)
message = n > 10 ? 'true' : 'false'
GC (garbage collection)

Collect objects that are no longer in use Automatically release memory


Alias method

Methods of the same implementation with different names


dvimod returns quotients and remainders as an array
14.divmod(3) #=> [4,2]
Omit block arguments if not needed
numbers.each do
    sum += 1
end
You can write ruby code in the block
numbers = [1,2,3,4]
sum = 0
    
numbers.each do |number|
    sum_value = n.even? ? n * 10 : n #Conditional operator
    sum += sum_value #sum_value is valid only within the block
end

sum #=> 64

By the way, when a professional writes it, it's so concise ...! !! !! @scivola, I will study.

numbers = [1,2,3,4]
sum = numbers.sum{ |n| n.even? ? n * 10 : n }

Reference: Array # sum (Ruby 2.7.0 Reference Manual)

Evaluate the elements of the array and make the return value a new array
numbers = [1,2,3,4]
new_numbers = numbers.map { |n| n * 10 }

new_numbers #=> [10,20,30,40]
Method to perform convolution operation
numbers = [1,2,3,4]
sum = numbers.inject(0) { |result, n| result + n }
#1st result result=>0, n=>1, 0+1=1
#2nd result result=>1, n=>2, 1+2=3

sum #=> 10
More concise with the &: method
[1,2,3,4].select { |n| n.odd? } #=> [1,3]
[1,2,3,4].select(&:odd?) #=> [1,3]
#1.When there is only one block argument
#2.When the method has no arguments
#3.Possible when the method is one sentence for the block argument
#&:Operator is useless
Range can also be used for strings
('a'...'e').to_a #=>["a","b","c","d"] ...Does not end
Specify the number of digits
'0'.rjust(5) 		#=> "    0"
'0'.rjust(5, '0')	#=> "00000"
Get the end of an array
a = [1,2,3]
a[-1] #=> 3
Replacement of array elements
a = [1,2,3,4,5]
a[1,3] = 100
#=> [1,100,5]Stupid...
Set of sum and difference products of arrays
a = [1,2,3]
b = [3,4,5]

a | b #=> [1,2,3,4,5]
a - b #=> [1,2]
a & b #=> [3]
Receive all remaining elements as an array with multiple assignment
e, f = 100, 200, 300
e #=> 100
f #=> 200

e, *f = 100, 200, 300
e #=> 100
f #=> [200, 300]
Synthesize the array
a = [1,2]
b = [3,4]

a.push(b) #=> [1,2,[3,4]]
a.push(*b) #=> [1,2,3,4]
Concisely create an array of strings using% notation
['apple', 'melon', 'orange']
#=> ['apple', 'melon', 'orange']

%W!apple melon orange!

%W(apple melon orange)

%W(
	apple
	melon
	orange
)
Initial value of array
a = Array.new(5, 'nil')
#=>[nil, nil, nil, nil, nil]
a = Array.new(5){'default'}
#=>["default", "default", "default", "default", "default"]
#=>All elements are different objects
Join arrays with join
names = ['Sato', 'Tanaka', 'beach']
honorific = names.map{ |name| "#{name}Mr."}
honorific.join('When') #=>"佐藤さんWhen田中さんWhen浜辺さん"
Escape the global area with catch and throw
last_names = ['Sato', 'Tanaka', 'beach']
first_names = ['Taro', 'Jiro', 'Minami']
catch :myfavorite do
    last_names.shuffle.each do |last_name|
        first_names.shuffle.each do |first_name|
            puts "#{last_name} #{first_name}Mr."
            if last_name == "beach" && first_name == "Minami"
				throw :myfavorite #symbol
            end
        end
    end
end

Recommended Posts

What impressed me as a beginner in writing Ruby
What is a Ruby module?
Multiplication in a Ruby array
Sorting hashes in a Ruby array
Implement a gRPC client in Ruby
What is a snippet in programming?
[Note] [Beginner] Ruby writing memo (refactoring) 1
What is a Ruby 2D array?
What is a class in Java language (3 /?)
I tried a calendar problem in Ruby
Differences in writing in Ruby, PHP, Java, JS
[Technical memo] What is "include" in Ruby?
What is a class in Java language (1 /?)
What is a class in Java language (2 /?)
What you need to know before writing a test in an iOS app
Escape processing when creating a URL in Ruby
AtCoder Beginner Contest 169 A, B, C with ruby
I made a Ruby extension library in C
What a beginner did to understand Object Orientation
(Ruby on Rails6) Creating data in a table
[Ruby] What if you put each statement in each statement? ??
Create a native extension of Ruby in Rust
Summary of what I was pointed out after receiving a code review as a beginner