⬆️ ⬇️

Ruby chips

I see many interested in the Ruby theme. And many are asking for more practice and more code. I decided to invest my 5 kopecks :) I will not write a lot of theory, but only show some interesting Ruby chips. After all, the main thing in Ruby is beauty.



1. Assigning values ​​to variables.

This is how it is possible to write in one line the assignment of values ​​to several variables.

x, y, z = 1, 2, 3


Result: x = 1, y = 2, z = 3





2. Exchange of variable values.

To exchange the values ​​of two variables, the third (z) is often used, which must temporarily store x values. In Ruby you can make it easier:

x, y = 1, 2

x, y = y, x


Result: x = 2, y = 1

')

3. If all the arguments of the arithmetic expression are integers, the result will be an integer, if at least one is a floating point number, the result will be a floating point.

Not quite an obvious move, and if you do not know about it, errors may occur. So, as a result of the expression 1/2, you expect to get 0.5, but Ruby will return 0. That is, round the result down to the whole.

1/2 # => 0

3/2 # => 1


To get the right results, you need at least one of the numbers to be fractional:

1.0 / 2 # => 0.5

3.0 / 2 # => 1.5


Other examples with other arithmetic operations:

10 - 5.0 # => 5.0

8 + 2.0 # => 10.0

2 * 5.0 # => 10.0




4. Working with strings as with arrays

Consider a simple example:

str = "Xabrahabr!" # Something is wrong, right?

str [0] = "H" # fix the error

puts str # => Habrahabr!


And get the right result!



5. Negative indexing in arrays.

How to get the last element of an array if the length is unknown? array [array.length-1]? And the penultimate? array [array.length-2]? Ruby has a better solution!

arr = [1, 2, 3, 4]

arr [-1] # => 4


Along with traditional positive array indexing, there is a negative in Ruby. The very last element has an index of -1, the penultimate -2, and so on. Just to remember: arr [-1] is the same as arr [arr.length-1], but with no arr.length :)



6. Is the array empty?

There are many ways to tell if an array is empty. But the logical and simplest is the logical method .empty?

arr = []

arr.empty? # => true




These are not all interesting Ruby chips. You can find more on Wikibooks and language blogs. Learn Ruby and share interesting discoveries with others.



In preparing the article used Wikibooks materials

Source: https://habr.com/ru/post/11104/



All Articles