We will conquer Ruby together! Drop of the seventh

    In this drop, we will once again go over all the topics we have examined and delve 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 on the new Startup programmer blog . The blog is intended for beginners and, possibly, “seasoned” programmers who want to learn step by step the first or ... a valuable programming language. Now keeping track of the drops is even easier!

    Input and inspect

    puts "What is your name?"
    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

    STDOUTIs a standard global constant denoting a standard output channel. The method flushclears all data in Ruby's internal I / O buffer. Using this line of code is optional, but recommended. Remember that all constants must start with a capital letter.

    getstakes one line of input and passes it to a variable. chompIs a class method String. Despite the fact that we see the same result, you must remember that it getsreturns a string and \n, while it chompdeletes this \n(the method also removes the carriage return \rand combination \r\n).

    It is easy to demonstrate this using a method inspectwhose role is to “look” into variables, classes - in general, into any Ruby objects.

    Punctuation in methods

    The exclamation mark 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 method stripremoves spaces at the end of the line:

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

    Methods with a question mark, the so-called predicates , return only trueor false, for example, the method of arrays empty?will return true if there are no elements in the array: The method will return if the elements are present in the array, but , defined in the class , will return if the number to which it is called is equal to zero, otherwise it will return this number.

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


    Use% w

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

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

    Condition Branching

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


    a = 7
    if a == 4
       a = 9

    But Ruby would not have been Ruby if he had not simplified our task. A completely similar cycle:

    a = 7
    a = 9 if a == 4


    Example condition:

    a = 7
    if a == 4
       a = 9
       if a == 7
          a = 10

    elsifsimplify this condition as much as possible and get:

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

    Triple operator

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

    The design [? (expr) : (expr)]is called the triple (ternary) operator (the only triple in Ruby) and serves to calculate the expression and returns the result. It is recommended to be used only for secondary tasks, since such code is hard to read. First, the first operand is calculated before ?, if its value is neither falseand not nil, the value of the expression becomes the value of the second operand, otherwise the third (after :).


    whilein Ruby syntax is similar to if, and whilein other PL:

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

    As usual cycle can be placed in one line:<...код...> while <выражение>


    In the code, Symbolit looks like a variable name, just starting with :, for example,: action. SymbolIs the simplest object in Ruby that can be created - it only has a name and ID. Symbol'y efektivnost more, productive than lines - this symbol name refers to the same object throughout the program, while the 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!"
       puts 'Learn Ruby!'

    In this example :yes- symbolhe does not contain values ​​or objects; instead, it is used as a constant name in the code. We can calmly replace it :yeswith a string "yes", the result will be the same, but the program will be less productive. You can learn more about the topic in a wonderful article by Kane.“The difference between characters and strings”

    Associative arrays

    Associative arrays (hereinafter, hashes) are similar to arrays, since they also contain 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, the hash elements are not ordered, so the hashes are not suitable for lists, queues, etc.

    Wherever you want to put a string in quotation marks, think about using symbol:

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


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

    Also popular now: