This is an article that summarizes the memos when I read the Cherry book.
If the variable (receiver) is nil, it returns nil, and if it is not nil, the processing on the right side is executed. It can be written concisely when used when it is uncertain whether the variable has a value or nil.
user = ‘suga’
p user&.upcase #=> SUGA
user = nil
p user&.upcase #=> nil
By the way, if you use the upcase method for nil as it is, the following error will occur.
user = nil
p usesr.upcase
undefined method `upcase' for nil:NilClass (NoMethodError)
#NoMethodError: no upcase method defined for nil object in NilClass
Unlike json, it doesn't manage strictly, so it seems to put a comma at the end of the array. It's like, "It doesn't matter which one you put a comma on = let's put it on!"
array = [
'hoge',
'fuga',
'piyo',
]
h={hoge: 'hoge', piyo: 'piyo'}
p a = { fuga: 'fuga', **h } #=> {:fuga=>"fuga", :hoge=>"hoge", :piyo=>"piyo"}
You can take a block as an argument by using proc inside
a = ['a','b','c']
p a.map(&:upcase)
[]
is returnedThis is often seen in source code such as rails. I will forget it every time, so I will write it as a memorandum. The following have the same meaning. The advantage is that it can be omitted.
test = nil
p test ||= 'hoge' #=> ‘hoge’
p obj.foo #=> nil
p obj.foo || (obj.foo = true) #=> true
test = nil
if test.nil?
p 'hoge'
else
p test
end #=> ‘hoge’
test = 'fugaaaaaaaaaaaa’
p test ||= 'hoge’ #=> ‘fugaaaaaaaaaaaa’
test = 'fugaaaaaaaaaaaa’
if test.nil?
p 'hoge'
else
p test
end #=> ‘fugaaaaaaaaaaaa’
Returns true if one or more conditions are met
array_and_nil = [1, 2, nil, nil, 5]
p array_and_nil.any?(&:nil?) #=> true
require 'active_support/all'
hoge = nil
def piyo(hoge)
hoge || return
end
piyo(hoge) #=> nil
tx = %w(1 2 3 4 5)
ty = %w(a b c d e)
for point in tx.product(ty)
p(point)
end
&: Code like below. You can omit the block to pass.
Conditions that can do this
n=[1,2,3,4,5,6]
n2=n.select(&:even?)
attr_accessor I personally read the name as an attribute accessor. People around me may say that they are accessors
To put it simply, the role is that you can write the following code in one line
def name
@name
end
def name=(name)
@name = name
end
The above 6 lines of code become the next 1 line
attr_accessor :name
self.class. [Class method]
class User
def self.self_
p 'self'
end
def instance_
self.class.self_
end
end
a = User.new
a.instance_ #=> 'self'
Overwrite method after creating alias for existing method ➡️ prepare?
A singular method (also called a singleton object) that connects only to a specific object
hoge = 'hoge'
def hoge.hello
p 'hoge!'
end
hoge.hello #=> 'hoge!'
include allows module methods to be called from an instance. make extend a class method
Recommended Posts