---
# System prepended metadata

title: Ruby Fundamentals - JS ==> Ruby

---

# Ruby Fundamentals - JS ==> Ruby

## Phase 3 at a High level

In Phases 1 and 2, we built a fundamental understanding of how to build out the frontend of a full stack web application. In Phases 3 and 4, we'll be pivoting to focus on building out the backend and connecting the two. At the beginning of this phase, we'll be focusing on Ruby as a language and how we manage data structures a bit differently than the way we did it in JavaScript. 

Here are the high level goals for the phase:
- to give you a sense of Object Oriented Programming and how it differs from functional programming. While we can do OOP in both Ruby and JavaScript, we've focused on functional programming in JavaScript up until this point. We'll be writing more object oriented code in Ruby.
- Understand the role of a database in a web application and how we can design a database that supports the features we want our application to have.
- Create a React application with multiple types of related data and connect to a database backed API built with Object Oriented Ruby code using the Sinatra web framework.
## My Focus as a Lecturer

Over the next few weeks, my goal is to help you all to practice your technical communication skills. One of the most challenging parts of learning to code is learning to adjust the way you speak to an unfamiliar degree of accuracy and precision. Your ability to think programmatically will improve as you practice using terminology to accurately describe what you're doing as you code. I want to help you all add good habits and skills to your toolbox so you are more effective–and happier–problem solvers. So, whenever you go into breakout rooms together, practice using terminology as you communicate rather than sounding out the syntax.

So, for example, if you were describing this code:

```rb
name = "Dakota"
```

instead of:

> name equals quotes Dakota end quote

we would say:

> declare a variable called name and assign its value to the string, Dakota.


## Questions to Carry around with you as you debug your code

- What am I trying to do?
- How do I get feedback about the current behavior?
- How can I explain what's happening now?
- How can I test my explanation?
- If my explanation is correct, what change can I make to get closer to my goal? When I make the change, what result should I get? (After I make the change and run the code) Was my explanation correct/complete?

When you watch professional athletes, you will see many variations of a pre-shot routine. 
- A basketball player before shooting a free-throw
- A runner before the start of a race
- A golfer preparing to tee off
- A batter preparing for the pitcher's windup.

Whatever the example, professional athletes develop a set of behaviors that prepare the mind for the task at hand. Approaching programming in the same way can make it a much more enjoyable experience. As you work with me over the next couple of weeks, one of my goals is to share ideas that you can integrate into your routine to develop solid mind patterns that set you up for success. 

In programming, I see this as a series of questions that you repetitively ask yourself in different situations that move your mind in the directions it needs to go to solve a given type of problem. Reading and talking about code are essential skills for any software engineer. I want to foster as much dialog as possible over the next few weeks, so please engage with each me and with each other to get the most out of the experience :) 

## How to Get Feedback in Ruby

- irb
- ./bin/console
- binding.pry

## Errors

### NameError

NameError (undefined local variable or method `friends' for main:Object)

NameError (uninitialized constant DateTime)

If you see `uninitialized constant` this probably means what?
- Did we misspell it?
- we need to require some file that loads the constant
- in this case we need to `require 'date'`

### ArgumentError
Traceback (most recent call last):
        3: from ./bin/console:14:in `<main>'
        2: from (irb):1
        1: from /Users/dakotamartinez/Development/flatiron/iterations/SENG-LIVE-062821/Phase-3/solutions/01_ruby_fundamentals/lib/ruby_fundamentals/playground.rb:16:in `add'
ArgumentError (wrong number of arguments (given 1, expected 2))

4 places to look here:
1. the given number of arguments
2. Expected number of arguments
3. Line number pointing to method definition
4. Line number pointing to where the method is called

Undefined method pry for binding?

```bash
bundle add pry
```

To make sure Gemfile has pry in it, and that you have a `require 'pry'` in your code.



## 

| Concept | JS | Ruby |
|---|---|---|
| Version Manager | nvm | rvm |
|  |  |  |
|  |  |  |

```bash
rvm use 2.7.0
```

## Topics

### Variables

How are variables defined in Ruby? How is it different from JS?
- Variable names are in snake case in ruby
- no keyword to define them (just name of variable)
    - no var, let, const

```rb
name = "Dakota"
```

```js
const name = "Dakota"
```

Constant in ruby:

```rb
NAME = "Dakota"
```

If we were to try to reassign a constant in Ruby:

```rb
NAME = "Zach"
```

### Functions/Methods 

What are some differences between Ruby methods and Javascript functions?

- Methods are defined with `def` keyword and `end`
- parentheses for parameters are not required in ruby
- always return something - implicit returns (even if we don't explicitly return a value)
- if you specify 2 parameters then 2 parameters are required. Arguments are required by default or we'll get an argument error
- Ruby methods cannot be referred to directly without invoking them
- If we iterate in JS with forEach, how does that work?
    - We pass what as an argument? Callback function

### Different data types: 

What are some data types in Ruby?

- Integer
- Float (instead of just Number)
- String
- Symbol => keys in a Hash
- Hash (like an object in JS)
- Arrays 
- Boolean
    - truthiness in ruby - 0, "", [], everything but nil, false
    - falsiness => `nil` and `false`
- Time
- Date
- DateTime
    
    
Truthy <-> Falsey in JS

Falsey values in JS
0
""
undefined
null


### When do I use an Array vs Hash

If we want indexes we'd use an array, if we need key value pairs we would use a hash.
Hash would be good for a profile:
first_name
last_name

data that's related that we want to add labels to.

When would we choose an array?
We can manipulate order more reliably.

Lets say we wanted to keep track of all of the episode of a TV show. What data structure might we use?

An array (of Strings or Hashes?)

- benefits of string?
    - easier to manipulate/sort
- challenges of strings?
    - limit to what we can store.
- benefit of hash?
    - the ability to store multiple pieces of info about episode.
- challenges of hash?
    - harder to access data
    - we need to know what the keys are in the has to get access.

What info would we want about an episode?

Who the actors are
the runtime
episode number
season number
airdate
title

## Hashes

```
friends.class #=> Hash
friends.keys #=> ["id", "url", "name", "type",
"language", "genres", "status", "runtime", 
"averageRuntime", "premiered", "officialSite",
"schedule", "rating", "weight", "network", 
"webChannel", "dvdCountry", "externals", "image", 
"summary", "updated", "_links", "_embedded"] 
```


### Hash vs JS object

What are the differences between hashes and objects?
- In Ruby keys can be multiple data types
- In JS keys are always strings
- How do we access values in a JS object?
    - dot notation
    - bracket notation
- In Ruby how do we access values inside of a hash?
    - bracket notation
    - dot notation doesn't work for access a key's values

```rb
NUM_MAP = {
    "one" => 1, 
    1 => "one", 
    "two" => 2, 
    2 => "two"
}
```

WE want to use the NUM_MAP to convert an integer to its word version. What do we do?

```rb
NUM_MAP[1] #=> "one"
NUM_MAP["one"] #=> 1
```


### Iteration

How do iterate in JS? How is it different in ruby?

| Concept | JS | Ruby |
|---|---|---|
| Basic | `forEach` | `each` |
| Transform | `map` | `map` (alias called `collect`) |
| Find first match | `find` | `find` (alias called `detect`) |
| Find all matches | `filter` | `filter` (aliases called `select` and `find_all`) |

### Gems installation and use

| Concept | JS | Ruby |
|---|---|---|
| Installing Individual Packages | `npm install react-router-dom` | `bundle add pry` |
| Viewing Dependencies | `package.json` | `Gemfile` |
| Installing All Packages | `npm install` | `bundle` or `bundle install` |
| Package Repository | npmjs.org | rubygems.org|
| Loading Dependencies | `import React from 'react'` | `require 'pry'`|
| Loading your own code | `import Navbar from './Navbar'` | `require_relative './lib/ruby_fundamentals/friends'` |

```rb
def get_episodes
  friends["_embedded"]["episodes"]
end
```


## Skills

### debug with irb & pry

### become familiar with ruby docs

### write and execute a ruby method

### access nested data from Hashes and Arrays with variable utilization

### use each, map, find, select

