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.
irb(main):001:0> 1.9.ceil => 2
irb(main):004:0> 1.9.floor => 1
irb(main):006:0> 1.5.round => 2 irb(main):007:0> 1.4.round => 1
The elements of the array are separated by the character specified by the argument, and the combined character string is returned.
arr = ["Useless", "Useless", "Useless", "Uselessァ", "Tsu!"] p arr.join("!") => "Useless!Useless!Useless!Uselessァ!!"
I'm stuck with a mock question. First from the code.
numbers = [3,89,40,39,29,10,50,59,69] num = numbers.inject do |i,j| i > j ? i : j end
When an argument is attached, the inject method assigns the argument to the first block variable (i) and the first element of the array to the second block variable (j). Execute the expression after do. When the execution is finished, assign the calculation result to i and the next element of the array to j. Execute the expression. After that, it repeats and returns the result when the elements of the array reach the end. If no argument is given, the first and second elements of the array are assigned before starting.
i > j ? i : j
After executing the expression on the left side (from? To the left) that asks the truth, put the value returned when true is on the left of (:) and the value returned when false is placed on the right of (:). So this expression means "returns i if i is greater than j, j otherwise". so, Since this is executed by the inject method, it becomes "code that compares the elements of the array, leaves a large number, and finally returns the largest number in the array".
1.step(100, 2) do |n| puts n end
Starting from the value of the receiver, the expression is executed in increments of the second argument until the value becomes the first argument. The numerical value of the receiver is entered as the initial value in the block variable n. When you translate the code, "After outputting the number" 1 "of the receiver (puts n), add 2 to the number and execute again (output 3). Run until this number reaches 100. " This time, odd numbers are output, and at the end, 99.2 is added and it exceeds 100, so it ends here. What you are doing is an odd number of outputs from 1 to 100.