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.
special_price = 200
puts "#{special_price}"
puts "\"Hello\""
#=> "Hello"
1_000_000_000
#=> 1000000000
1 / 2 #=>0
1.0 / 2 #=>0.5
n += 1 #=>2
n *= 3 #=>6
n /= 2 #=>3
n **= 2 #=>9
0.1 * 3.0 == 0.3 #=>false
0.1 * 3.0 <= 0.3 #=>false
0.1r * 3.0r #=>(3/10)
greeting =
if
elsif
else
end
if (processing) then (Return value)
%q!! #=> ' '
%Q!! #=> " "
%!! #=> " "
a = <<TEXT
String
TEXT
'%0.3f' % 1.2 #=>"1.200"
2e-3 #=> 0.002
#2×10^-3
message = n > 10 ? 'true' : 'false'
Collect objects that are no longer in use Automatically release memory
Methods of the same implementation with different names
14.divmod(3) #=> [4,2]
numbers.each do
sum += 1
end
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)
numbers = [1,2,3,4]
new_numbers = numbers.map { |n| n * 10 }
new_numbers #=> [10,20,30,40]
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
[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
('a'...'e').to_a #=>["a","b","c","d"] ...Does not end
'0'.rjust(5) #=> " 0"
'0'.rjust(5, '0') #=> "00000"
a = [1,2,3]
a[-1] #=> 3
a = [1,2,3,4,5]
a[1,3] = 100
#=> [1,100,5]Stupid...
a = [1,2,3]
b = [3,4,5]
a | b #=> [1,2,3,4,5]
a - b #=> [1,2]
a & b #=> [3]
e, f = 100, 200, 300
e #=> 100
f #=> 200
e, *f = 100, 200, 300
e #=> 100
f #=> [200, 300]
a = [1,2]
b = [3,4]
a.push(b) #=> [1,2,[3,4]]
a.push(*b) #=> [1,2,3,4]
['apple', 'melon', 'orange']
#=> ['apple', 'melon', 'orange']
%W!apple melon orange!
%W(apple melon orange)
%W(
apple
melon
orange
)
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
names = ['Sato', 'Tanaka', 'beach']
honorific = names.map{ |name| "#{name}Mr."}
honorific.join('When') #=>"佐藤さんWhen田中さんWhen浜辺さん"
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