[Ruby] Ruby learning points (basics)

2 minute read

-Enclose the character string in quotation marks (‘or “), and be sure to write quotation marks in half-width characters.

  • It is necessary to open a space after puts.

  • Comment out “#” at the beginning of the line *Multi-line comment out mac: “command + /” windows: “ctlr + /”

  • The variable must be used only after defining the variable (variable name = value). (Because the programs are executed sequentially from the top)

  • Variable names can be freely decided, but there are some naming rules in Ruby. In particular, use an underscore (_) when giving a variable name that is a combination of two or more words.

  • There is a way to include the value of a variable in a string. By using #{variable name} in the character string, you can replace the variable with the assigned value and include it in the character string. This is called “variable expansion”.

  • Variable expansion is performed only for a character string that uses double quotes. Note that in the case of single quotation, variable expansion is not performed and it is output as it is as a character string.

  • Since the array also has one value, it can be assigned to a variable. By convention, variable names that assign arrays are often in the plural.

  • Use each statement for iterative processing. By using each statement, you can take out the elements of the array in order and process them. Write each array as “array.each do variable name ”, and write the process you want to execute before “end”.
    The each statement iterates over the number of array elements. The elements of the array are entered one by one in the variable enclosed by “ ”, and the processing in each statement is executed on it. You can give any name to the variable name in each statement, but it is customary to use the singular form of the array variable names.  
  • The usable range of each variable is called a scope.

  • In the hash, you can also write the key part with a colon “:” at the beginning instead of a character string, as shown in the figure below. This form of “:name” is called a symbol. A symbol is a writing method in which characters are prefixed with “:” instead of being surrounded by “”” or “’”. Strings and symbols are strictly different, but basically they can be used in the same way.

  • When you use a symbol for the hash key, you can omit it. Specifically, “:key =>” can be omitted as “key:”. Even if you omit it, the key is a symbol, so you need to use a symbol like puts user[:name] to get an element.

  • Within an instance method, “self” refers to the instance itself.

  • An explicit receiver is required to call the method. In the case of class method, self is specified as the receiver.

  • Unique value for each instance: Instance variable Common value for each instance: Class variable