< Language Tutorials

Document.png Please expand this article or section. You can help by adding more information if you are an editor. More information might be found in a section of the talk page. (August 2018)

In this part of the Ruby tutorial, we will be learning about variables, arrays, and hashes in Ruby, and how they relate to their equivelents in Scratch.

Variables

Variables are shown as (var_name) in Scratch. They are crucial in all programming languages, including Ruby.

Creating a New Variable

The button used to create a variable in Scratch.

In Scratch, you create a new variable inside the editor with the "Make a Variable" button, and by typing in the name of the variable, and choosing some options for the variable. In Ruby, variables are created in the actual text, like this: var_name = value

Changing the Value of a Variable

In Scratch, a variable's value is changed with the set [var_name v] to (value) block. In Ruby, variables are changed the same way they are created; with var_name = value.

Arrays

Arrays are Ruby's equivalent to lists in Scratch.

A list in Scratch.

Creating a New Array

In Scratch, lists can be created using the "Make a List" button, similar to the "Make a Variable" button, but for lists. Then one must fill in the name of the list, and choose the appropriate options. In Ruby, arrays can either be created with the array_name = Array.new syntax (with no values inside them), or with this syntax: array_name = [item_in_array, item_in_array, etc.]

Adding Items to Arrays

Similar to the add [item] to [list name v] block in Scratch, values can be added to arrays with this syntax: array_name.push(value or variable)

Hashes

You can recreate hashes in Scratch by using two lists as one, with item one of the first list associated with item one of the other list, item two associated with item two, etc.

Basically, hashes are a data type similar to an array, but instead of one item per slot, there are two. One is called a "key", and one a "value".

Creating a New Hash

Like arrays, hashes can be created by using hash_name = Hash.new, but they also can be created using the following syntax:

hash_name = {
key => value,
key => value,
key => value,
etc.
}

One more way to create a hash uses symbols, which will be explained in a later tutorial. However, here is the syntax right now:

hash_name = {
key: value
key: value
key: value
etc.
}

Example:

person = {
"name" => "John",
"age" => 36
}

Adding Keys and Values to Hashes

Keys and values can be added to Hashes using .push, just like in arrays. However, the syntax is different: hash_name.push(key, value)

Cookies help us deliver our services. By using our services, you agree to our use of cookies.