# Ruby Niceties

## Creates numbers quickly

```[*1..10]

# other way around

10.step(by: -1, to: 0).to_a
```

## Sort Reversely

```[*1..10].sort_by(&:[email protected])
```

The `[email protected]` is called unary operator.

## Rational and Complex Number

From Rational and Complex module.

```42r # Rational(42, 1)
3.14r # 3.14.rationalize

42i # Complex(0, 42)
3.14i # Complex(0, 3.14)

3r + 4i
```

Since Ruby 2.1.

## Function Compositions

`<<` and `>>` from Ruby 2.6.0.

```plus_two = proc { |x| x + 2 }
three_times = proc { |x| x * 3 }
(plus_two << three_times).call(3) # plus_two(three_times(3))
(plus_two >> three_times).call(3) # three_times(plus_two(3))
```

## Initialize Struct with keyword arguments

```User = Struct.new(:name, :handle, keyword_init: true)
User.new(name: "Juanito Fatas", handle: "JuanitoFatas")
```

Since Ruby 2.5: Feature#11925.

## Endless Range

```array[1..]
(1..).each {|i| puts i }
```

Since Ruby 2.6: Feature#12912

## Beginless Range

```array[..42]
(..42).each {|i| puts i }
```

Since Ruby 2.7.

## Count number of elements in array

```["a", "b", "c", "b"].tally
#=> {"a"=>1, "b"=>2, "c"=>1}
```

Since Ruby 2.7.

## Delegate arguments

```def parent_method(...)
child_method(...)
end
```

```def parent_method(*args, **options, &block)
child_method(*args, **options, &block)
end
```

Since Ruby 2.7: Feature#16253.

## Transform hash keys and values

```{ a: 1, b: 2 }.transform_keys(&:to_s)
=> { "a" => 1, "b" => 2 }

{ a: 1, b: 2 }.transform_values(&:to_f)
=> { a: 1.0, b: 2.0 }
```

`transform_values` Since Ruby 2.4.
`transform_keys` Since Ruby 2.5.