-
Notifications
You must be signed in to change notification settings - Fork 41
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
149 changed files
with
1,606 additions
and
449 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
File renamed without changes.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,73 @@ | ||
--- | ||
|
||
name: Логический тип | ||
theory: | | ||
## Логические операторы | ||
Логический тип в Ruby представлен привычными значениями `true` и `false`, а так же набором операторов `&&` (и), `==` (равно), `||` (или) и `!` (не): | ||
```ruby | ||
true && false # false | ||
fales || true # true | ||
``` | ||
В отличии от многих других языков, сравнение с логическим значением в Ruby строгое, то есть `true` и `false` равны только самим себе: | ||
```ruby | ||
true == 1 # false | ||
false == nil # false | ||
``` | ||
Что не отменяет возможности использовать в логических выражениях значения любых типов: | ||
```ruby | ||
0 && 'one' # "one" | ||
nil && false # nil | ||
``` | ||
В Ruby только `nil` и `false` рассматриваются как *falsey*, все остальные значения в логических выражениях приводятся к `true`. | ||
## Значение по умолчанию | ||
В Ruby широко используется такой код: | ||
a ||= 'что-то' | ||
# a = a || 'что-то' | ||
Он используется для задания значения по умолчанию. Такое возможно и, почти всегда безопасно, из-за очень ограниченного списка *falsey* значений. Единственное место где этот способ не сработает – там где `false` это допустимое значение. | ||
## Предикаты | ||
В Ruby, в отличии от большинства других языков, принято использовать предикаты практически для всех часто встречающихся проверок. Например, как мы обычно проверяем, что число равно нулю? С помощью сравнения с нулем. В Ruby это тоже работает, но это не Ruby way: | ||
```ruby | ||
0.zero? # true | ||
1.zero? # false | ||
2.positive? # true | ||
# чётное/нечётное | ||
8.even? # true | ||
8.odd? # false | ||
''.empty? # true | ||
'wow'.empty? # false | ||
something.nil? | ||
# не пустой массив | ||
items.any? | ||
# пустой массив | ||
items.empty? | ||
``` | ||
instructions: | | ||
Реализуйте функцию, которая проверяет является ли переданное число четным. Не используйте встроенные функции для определения четности: | ||
```ruby | ||
even?(5) # false | ||
even?(6) # true | ||
``` | ||
tips: [] |
3 changes: 3 additions & 0 deletions
3
modules/20-arrays/20-arrays-each/index.rb → modules/10-basics/27-conditions/index.rb
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,4 +1,7 @@ | ||
# frozen_string_literal: true | ||
|
||
# BEGIN | ||
def even?(a) | ||
(a % 2).zero? | ||
end | ||
# END |
6 changes: 4 additions & 2 deletions
6
modules/20-arrays/20-arrays-each/test.rb → modules/10-basics/27-conditions/test.rb
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,10 +1,12 @@ | ||
# frozen_string_literal: true | ||
|
||
require 'test_helper' | ||
require './index' | ||
require_relative './index' | ||
|
||
describe 'function' do | ||
it 'should works' do | ||
# assert { double(3) == 6 } | ||
assert { !even?(1) } | ||
assert { even?(2) } | ||
assert { !even?(9) } | ||
end | ||
end |
File renamed without changes.
File renamed without changes.
File renamed without changes.
2 changes: 1 addition & 1 deletion
2
modules/10-basics/30-conditions/test.rb → modules/10-basics/30-if/test.rb
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
File renamed without changes.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,64 @@ | ||
--- | ||
|
||
name: Условные конструкции (альтернативные варианты) | ||
theory: | | ||
Ruby поддерживает множество видов условных конструкций, которые иногда способны сделать код чуть проще и прямолинейнее. Все они встречаются в реальном коде регулярно. | ||
## Тернарный оператор | ||
Работает и выглядит аналогично другим языкам: | ||
```ruby | ||
# <expr1> ? <expr2> : <expr3> | ||
v = 3 == 4 ? 1 : 0 | ||
``` | ||
## Постфиксный if | ||
В Ruby иф может стоять не только в начале, но и в конце выражений: | ||
```ruby | ||
doSomething() if num.zero? | ||
``` | ||
Подобную форму записи принято использовать тогда, когда все выражение помещается в одну строчку. | ||
## Unless | ||
В дополнение к *if*, в Ruby, есть конструкция *unless*, которая работает в обратную сторону: | ||
```ruby | ||
# Пока (если) something не zero? | ||
unless something.zero? | ||
# что-то делаем | ||
end | ||
``` | ||
*unless* позволяет избавляться от отрицаний, но с ним нужно быть осторожным. Если в предикате используется составное логическое выражение, то *unless* становится не читаемым: | ||
```ruby | ||
# Попробуйте осознать этот код | ||
unless a && b | ||
end | ||
``` | ||
instructions: | | ||
Реализуйте функцию `get_sentence_tone()`, которая принимает строку и определяет тон предложения. Если все символы в верхнем регистре, то это вопль — `'scream'`. В ином случае — нормальное предложение — `'general'`. | ||
Примеры вызова: | ||
```ruby | ||
get_sentence_tone('Hello') # general | ||
get_sentence_tone('WOW') # scream | ||
``` | ||
Алгоритм: | ||
1. Сгенерируйте строку в верхнем регистре на основе строки-аргумента с помощью метода `upcase`. | ||
2. Сравните её с исходной строкой: | ||
- Если строки равны, значит, строка-аргумент в верхнем регистре. | ||
- В ином случае — строка-аргумент не в верхнем регистре. | ||
tips: [] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,7 @@ | ||
# frozen_string_literal: true | ||
|
||
# BEGIN | ||
def get_sentence_tone(sentence) | ||
sentence.upcase == sentence ? 'scream' : 'general' | ||
end | ||
# END |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,12 @@ | ||
# frozen_string_literal: true | ||
|
||
require 'test_helper' | ||
require_relative './index' | ||
|
||
describe 'function' do | ||
it 'should works' do | ||
assert { get_sentence_tone('WOW') == 'scream' } | ||
assert { get_sentence_tone('WOw') == 'general' } | ||
assert { get_sentence_tone('Hexlet') == 'general' } | ||
end | ||
end |
File renamed without changes.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
File renamed without changes.
Oops, something went wrong.