📜 ⬆️ ⬇️

Let's beat Ruby together! Drop seven

In this drop we will once again go over all the topics we have considered and dive into them in search of the lost and interesting.

Attention! This is the last straw posted on the Ruby blog! All the past ( 1 , 2 , 3 , 4 , 5 , 6 ) are already sitting in the new blog Startup Programmer . The blog is intended for beginners and, perhaps, "experienced" programmers who want to learn step by step the first or ... the whole programming language. Now follow the drops even easier!


Input and inspect


puts "What is your name?"
STDOUT.flush
chompname = gets.chomp
puts "Again, what is your name?"
name = gets
puts "Hello, " + name
puts "Hi, " + chompname
puts 'But name = ' + name.inspect + ' and chompname = ' + chompname.inspect


STDOUT is a standard global constant denoting a standard output channel. The flush method clears all data in the internal Ruby I / O buffer. Using this line of code is optional, but recommended. Remember that all constants must begin with a capital letter.
')
gets accepts one line of the entered data and transfers it to a variable. chomp is a method of class String . Despite the fact that we see the same result, it must be remembered that gets returns a string and \n , while chomp removes this \n (the method also removes the carriage return \r and the combination \r\n ).

It is easy to demonstrate this using the inspect method, whose role is to “look into” variables, classes — in general, into any Ruby objects.

Punctuation in methods


The exclamation point at the end of the method means that it not only returns the result, but also changes the object to which it is applied (this is the so-called “dangerous” method). The strip method removes spaces at the end of the line:

 string = 'Bring, bring ' a = string.strip! puts string puts a 


Methods with a question mark, so-called predicates , return only true or false , for example, the empty? returns true if there are no elements in the array:

a = []
puts "empty" if a.empty?


Method any? on the contrary, it returns true if elements are present in the array, and nonzero? , defined in the Numeric class, will return nil if the number to which it is called is zero, otherwise returns this number.

Use% w


Sometimes creating an array of words can be a big headache, however in Ruby there is a simplification for this: %w{} does what we need:

pets1 = [ 'cat', 'dog', 'snake', 'hamster', 'rat' ]
pets2 = %w{ cat dog snake hamster rat } # pets1 = pets2


Branching conditions


We have already said that conditional expressions allow you to control the direction of code execution. We repeat these expressions and learn new ones.

if

 a = 7 if a == 4 a = 9 end 


But Ruby would not be Ruby if he did not simplify our task. Completely similar cycle:

a = 7
a = 9 if a == 4


if-elsif-else

Example conditions:

 a = 7 if a == 4 a = 9 else if a == 7 a = 10 end end 


elsif make this condition as simple as possible and we get:

 a = 7 if a == 4 a = 9 elsif a == 7 a = 10 end 


Triple operator

a = 7
plus_minus = '+'
print "#{a} #{plus_minus} 2 = " + (plus_minus == '+' ? (a+2).to_s : (a-2).to_s)


Construction [? (expr) : (expr)] [? (expr) : (expr)] is called a triple (ternary) operator (the only triple in Ruby) and is used to calculate the expression and return the result. It is recommended to use only for minor tasks, since such code is hard to perceive. Is the first operand counted first ? , if its value is not false and not nil , the value of the expression becomes the value of the second operand, otherwise - the third (after : .

while


while in Ruby is syntactically similar to if and while in other PLs:

 a = 0 while a < 5 puts a.to_s a += 1 end 


As usual, the loop can be placed in one line: <......> while <>

Symbols (Symbols)


In code, Symbol looks like a variable name, just starting with : for example:: action. Symbol is the simplest object in Ruby that it is possible to create - it has only a name and an ID . Symbols are more efficient, productive than strings — this name for symbol refers to one object throughout the program, while two lines with the same content are different objects — this saves time and memory:

 ruby_know = :yes if ruby_know == :yes puts "You're a good guy!" else puts 'Learn Ruby!' end 


In this example :yes is a symbol , it does not contain values ​​or objects, instead it is used as a constant name in the code. We can calmly replace :yes with the string "yes" , the result will be the same, but the program will be less productive. You can find out more about the topic in the wonderful article from Kane “The Difference Between Characters and Strings.”

Associative arrays


Associative arrays (hereinafter, hashes, hashes) are similar to arrays, as they also generate an ordered set of objects. However, in an array, objects are indexed by numbers, and in a hash, an index can be any object. A simple example:

 h = {'dog' => 'sobaka', 'cat' => 'koshka', 'donkey' => 'oslik'} puts h.length # 3 puts h['dog'] # 'sobaka' puts h # catkoshkadonkeyoslikdogsobaka 


As you can see, hash elements are not ordered, so hashes are not suitable for lists, queues, etc.

Wherever you want to put the string in quotes, think about the use of symbol :

users = Hash.new
users[:nickname] = 'MaxElc'
users[:language] = 'Russian'
puts users[:nickname] #MaxElc


Epilogue


Another small and interesting piece of data needed for our further development in Ruby. Comments are welcome!

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


All Articles