As I was studying, various kinds of each came out. I will write it so as not to forget it. : sunny:
fruits = [ "apple", "orange","banana"]
fruits.each do |fruit|
p fruit
end
#=>"apple"
# "orange"
# "banana"
fruits = { apple: 100, orange: 200, banana: 300}
fruits.each do |key, value|
puts "#{key}The price of#{value}It is a circle."
end
#=>"The price of apple is 100 yen."
# "The price of orange is 200 yen."
# "The price of banana is 300 yen."
It can also be described as follows. (If you like. When writing a long block, write ⇧ like before, if you want to write compactly, ⇩)
fruits = { apple: 100, orange: 200, banana: 300}
fruits.each { |key, value| puts "#{key}The price of#{value}It is a circle."}
#=>"The price of apple is 100 yen."
# "The price of orange is 200 yen."
# "The price of banana is 300 yen."
It is used when you want to retrieve only the key.
fruits = { apple: 100, orange: 200, banana: 300}
fruits.each_key {|key| p "#{key}Price" }
#=>"Apple price"
# "Price of orange"
# "banana price"
It is used when you want to retrieve only value.
fruits = { apple: 100, orange: 200, banana: 300}
fruits.each_value { |value| p "#{value}Circle"}
#=>"100 yen"
# "200 yen"
# "300 yen"
fruits = [ "apple", "orange","banana"]
fruits.each_with_index do |a,i|
p "#{i}Of#{a}there is."
end
#=>"There are 0 apples."
# "There is one orange."
# "There are two bananas."
fruits = [ "apple", "orange","banana"]
fruits.each.with_index(5) do |a,i|
p "#{i}Of#{a}there is."
end
#=>"There are 5 apples."
# "There are 6 oranges."
# "There are 7 bananas."
Specify the number in the argument. By doing so, you can slice the specified number as the name suggests and retrieve the element.
fruits = [ "apple", "orange", "banana", "lemon","lime"]
fruits.each_slice(2) do |fruit|
p fruit
end
#=>["apple", "orange"]
# ["banana", "lemon"]
# ["lime"]
It can be taken out separately at the line break.
fruits = "apple\norange\nbanana\nlemon"
fruits.each_line {|line| p line.chomp }
#=>[:apple, :orange, :banana, :lemon]
Evaluates the object and element of the argument and finally returns the object of the argument.
arr = [1, 2, 3]
result = arr.each_with_object({}) do |item, memo|
memo[item] = item + 1
end
p result
#=>{1=>2, 2=>3, 3=>4}
`This is further as Fukahori. .. ``
-What is the difference between inject and each_with_object?
I found that there are various types of friends in each. Let's expand the range that can be remembered little by little ...! !! : fire:
Recommended Posts