Categories
Dev Bootcamp

From Ruby Hashes to JavaScript Object Literals

From the perspective of someone who has a primer on Ruby and jumping onto JavaScript, I noticed something used very often in Ruby that is missing from JavaScript: Ruby Hashes. How can such a powerful data type not exist in other object-oriented languages? If you are also completely new to JavaScript and have the same question, fear not! There is something in JavaScript we can use to achieve the same features provided by Ruby Hashes: JavaScript Object Literals.

MDN defines an object literal as “a list of zero or more pairs of property names and associated values of an object.” As you can see from the definition, this is very similar to Ruby Hash‘s pairs of keys and associated values.

Here is a side-by-side comparison of creating, reading, changing, adding, and deleting a new JavaScript object literal versus a new Ruby hash literal:

JavaScript Object Literal:

//creating new JS object literal
var capitals = { spain: "Madrid",
  france: "Paris",
  italy: "Rome",
  hungary: "Budapest",
  germany: "Berlin"
};

//accessing JavaScript object value
capitals["france"]; //returns "Paris"
capitals["belgium"]; //returns undefined

//changing values
capitals["france"] = "Nice";

//adding a new property/value pair
capitals["russia"] = "Moscow";

//deleting a property/value pair
delete capitals["italy"];

//final result
console.log(capitals);
/*
prints:
{ spain: 'Madrid',
  france: 'Nice',
  hungary: 'Budapest',
  germany: 'Berlin',
  russia: 'Moscow' }
*/
Ruby Hash Literal:

#creating new Ruby Hash literal
capitals = { spain: "Madrid",
  france: "Paris",
  italy: "Rome",
  hungary: "Budapest",
  germany: "Berlin"
}

#accessing Ruby hash value
capitals[:france] #returns "Paris"
capitals[:belgium] # returns nil

#changing values
capitals[:france] = "Nice"

#adding a new key/value pair
capitals[:russia] = "Moscow"

#deleting a key/value pair
capitals.delete(:italy)

#final result
p capitals
=begin
prints:
{:spain=>"Madrid", :france=>"Nice", :hungary=>"Budapest", :germany=>"Berlin", :russia=>"Moscow"}
=end

See how similar they both are? Creating a JavaScript object literal is almost the same as creating a Ruby hash literal. It is important to note that while Ruby hash keys can be any data type (i.e. symbols, strings, integers, hashes, etc.), JavaScript object properties can only be variables. But they can point to any data type value, just like in Ruby hashes.

You can call a JavaScript object’s properties in a similar fashion as you would a Ruby hash‘s keys. Same with creating and deleting key/value and property/value pairs. Calling a non-existent key or property will return nil or undefined.

Note that while I used the bracket notation here to access and modify a JavaScript object’s properties, you can also use a dot notation. For a more in-depth explanation of the differences between the two types of notation, take a look at this medium article.

The next time you find yourself working with JavaScript and are looking to implement something similar to Ruby Hashes into your script, JavaScript object literals will fit the bill perfectly.

This blog has been initially published on tonymai.github.io.

Categories
Dev Bootcamp

Ruby Classes, Instances and Inheritance

Launch Your Understanding From 0-60 with Ruby Classes

Just as with any object-oriented programming language, class is an important part of Ruby. Everything in Ruby revolves around objects, and all of these objects belong to a class. Unlike in other languages, where each object can have multiple classes, objects in Ruby can only belong to one class. A class is a structure containing similar properties that each instance in the class share, but each instance can have different characteristics for those properties. Arrays, Hashes, and Strings are all examples of classes!

I threw out a lot of terminology, so let me show you an example:

class SuperCar
  def initialize(make, model, year, horsepower, torque)
    @make = make
    @model = model
    @year = year
    @hp = horsepower
    @tq = torque
  end
  def print_specs
    puts "This #{@year} #{@make} #{@model} has #{@hp} horsepower and #{@tq} lb-ft of torque."
  end
end

car_1 = SuperCar.new('Ferrari','458 Italia',2013,570,398)
car_2 = SuperCar.new('Lamborghini','Aventador',2012,691,508)
car_3 = SuperCar.new('McLaren','MP4-12C',2014,616,443)

There are several pieces of code to look at here. We have a class called SuperCar and three instances called car_1, car_2, and car_3. To define a new class, we began by writing the keyword class and then the constant SuperCar. Note that the constant for a class MUST start with a capitalized letter.

The class SuperCar contains the general structure and functions that each instance of this car has. This means that car_1, car_2, and car_3 each has the variables @make, model, @year, @hp, and @tq; and can use the methods initialize and printer_specs. It is important to note that car_1, car_2, and car_3 are not just limited to just these two methods. There are other ways to add new methods to these objects, which are not covered in this post.

Another thing that you see here are instance variables. They are the “properties” of the class, and each instance of the class has a different set of instance variables (i.e. car_1’s @make is Ferrari while car_2’s @make is Lamborghini). Instance variables can be used anywhere within the instance of the class. In the example, the initialize method stores the 5 parameters from initializing a new SuperCar into 5 instance variable assignments. These instance variables can be used in the print_spec method, as well as any other method you decide to create from within the class.

You’d call an instance method that you’ve created in the new class with the . notation, the same way you’d call an instance method from the built-in classes, such as Integers, Arrays, and Hashes. Here is an example of an instance method call and what is displayed on the console:

car_1.print_spec
>>"This 2013 Ferrari 458 Italia has 570 horsepower and 398 lb-ft of torque."
ar_2.print_spec
>>"This 2012 Lamborghini Aventador has 691 horsepower and 508 lb-ft of torque."

While an object cannot belong to more than one class, a class can be a descendant of another class. Descendant classes inherit all of the instance methods from the ancestor class, as well as the ancestor of the ancestor class, and so on.

For example, a certain super car collector takes a portion of his super cars to the racetracks:

class TrackCar < SuperCar
  def set_laptime=(time)
    @laptime = time
  end
  def get_laptime
    @laptime
  end
end

car_4 = TrackCar.new('Ferrari','458 Italia Speciale',2014,597,398)

Again, we have several pieces of code to look at here. In the first piece, I created a class called TrackCar and used the < notation to specify that TrackCar is a descendant of the SuperCar class. This class has two methods: set_laptime (this is a setter method) and get_laptime (and this is a getter method). A setter method allows you to set an instance variable to a value and a getter method allows you to get the value of an instance variable.

Notice that the set_laptime method looks a little funky. Ruby allows you to use the = notation in instance methods to make calling it look more reader-friendly and consistent with variable assignment conventions (i.e. car_4.set_laptime = 98 as opposed to car_4.set_laptime(98)). There is another shortcut to write setter and getter methods, using attr_ attributes (to learn more about them, you can start here).

In the last piece of the code, I created an instance of TrackCar called car_4. Now, let’s run several methods:

car_4.print_specs
>>"This 2014 Ferrari 458 Italia Speciale has 597 horsepower and 398 lb-ft of torque."
car_4.set_laptime = 98
puts "This car's fastest lap time is #{car_4.return_laptime} seconds."
>>"This car's fastest lap time is 98 seconds."

Notice that the print_specs method works even though it was not written in the TrackCar class. This is because TrackCar is a descendant of SuperCar. Any instance of the class TrackCar can use methods from its ancestor classes. If you do not specify an ancestor class, it will default to the class Object. Object is a descendant of BasicObject, which is at the top of the Ruby class hierarchy. That means that all Ruby classes eventually go up to Object and then BasicObject.

This is a good place to stop. We’ve talked about classes, instances, instance variables, instance methods, and class inheritance. To summarize it all, as tutorialspoint puts it, “A class is essentially a blueprint from which individual objects are created.”

This blog has been initially published on tonymai.github.io.

Categories
Dev Bootcamp

Drug Addiction in the Tech World

“People graduate to doing things that they never thought they would have done.” – Michael Johnson

While doing some research on cultural problems facing the tech world, I found all kinds of issues that are common: women in technology, brogrammers, sexism and sexual harassments, lack of diversity and cultural awareness, lack of respect for public (i.e. Facebook’s mood manipulation experiments), preference of hiring the young and inexperienced, etc. One thing that caught my attention was something that haven’t came up in the news that often; the common use of illicit drugs in Silicon Valley.

This is interesting to me, especially in light of the recent overdose death of an executive at Google, a company that I consider to be an industry leader in the tech world. Forrest Hayes, a Google executive and father of five, was found dead on his yacht in Santa Cruz this past summer. It is not surprising to me that drug abuse is common amongst many in the tech industry, but I don’t hear about it in the news that much, so I decided to do some further research.

Tech workers in the valley are faced with many forces; a fast-paced, overworked environment that values rapid productivity with tight deadlines and intense competition. There is a term called the “10x engineer” (an engineer that is 10x more productive than a 1x engineer) in the startup world. Engineers who are willing to work longer, harder, and produce more capital; engineers who are chasing the high of the win. This, combined with monetary and cultural incentives, leads to tech workers exploring the use of illicit drugs, like Adderall, for performance-enhancing purposes. Adderall is so common in the industry that it is normalized as something that is “at best, a stronger version of caffeine, and at worst, a more socially acceptable alternative to cocaine,” says Cori Johnson

Adderall isn’t the only drug common in the tech industry. Many high-level executives (from companies like Google, Apple, Twitter, Facebook, and Yahoo) are struggling with everything, from cocaine and heroin to black-market painkillers. Detox specialists say that progression up the addiction ladder is predictable. It starts with caffeine, like Red Bulls and Monster energy drinks. When caffeine is not enough, they turn to stimulants, like Adderall, to get amped up, and then depressants, like oxycodone, to take the edge off. Eventually, they would get used to the effects of the pills and then turn to heroin; first smoke/snort, then, as their bodies build up tolerance, inject. “People graduate to doing things that they never thought they would have done,” said Michael Johnson.

Many tech companies do little or no drug testing, and managers look the other way. “They want the results, but they don’t want to know how their employees got the results,” says Steve Albrecht. This is a fundamental culture problem; and it won’t be fixed unless the environment supports it. These problems come from a broken business model that puts results over its employees. The intense competition drives managers to put pressure onto its employees. The tech world has a rampant drug problem and it’s sad to see that it took the death of a high-level executive for the media to bring this problem to the forefront. While I do not see big tech companies or even the numerous funds-strapped startups implement policies to reduce this kind of behavior anytime soon, we have to start somewhere.

Further Reading:

This blog has been initially published on tonymai.github.io.

Categories
Dev Bootcamp

A Tear-Down of the Enumerable map Method

What does map do?

Here is the map method:

map { |item| block }

And here is what it returns:

#=> new_array

Essentially, map is an Enumerable method that runs a code block once for each element of the object and returns a new array of of the results of the block.

If you’re just starting to learn programming, you may be asking, “what does this really mean?” Let me try to break it down.

Enumerable provides collection classes with several searching and sorting methods. Arrays and Hashes are two examples of classes that have Enumerable properties, and therefore, can use Enumerable methods. map is one of those Enumerable methods.

What does it really mean? I work out.

Here is an example senario and code:

benched_weights = [90,140,160,120,165]
benched_weights.map { |wt| wt + 45 } 
#=> [135,185,205,165,210]

One the first line of the code, you’re keeping track of how much weight you are putting onto the barbell when you bench on chest days. You are storing this in an array called benched_weights. On the first day, you put 90lbs on the bar. On the second day, you put 140lbs on the bar. Third day, 160lbs. You had a bad day on the fourth day and only put 120 lbs on the bar. And so forth…

Now, let’s say, you want to see how much weight you are benching in total, including the weight of the barbell itself. The barbell weighs 45lbs. On the second line if the code, you used the map method. You assigned the variable wt in between the pipes as a placeholder for each element in the Array and then a code block that says wt + 45. What the code is doing here is going through each weight that you logged and adding 45 to it.

During the first pass, wt is equal to the first element of the array, which is 90, and then returns wt + 45, which is 135. After the first pass, it loops to the second element, which is 140, and then returns wt + 45, which is 185. Third pass, the wt is 160 and returns wt + 45, which is 205, and so on until it goes through each element in the given array.

When all is said and done, the map method will return all of the values given by the code block in the form of a new Array, which is shown on the third line.

As a side note, you can also use Enumerable#collect interchangeably with #map. They are completely synonymous (i.e. benched_weights.collect { |wt| wt + 45 }.

How does this compare to “each”?

Many beginner’s Ruby books and courses use the each method as an introduction to teach iterators and code blocks. If you are familiar with the Array each method, you’ll notice that the Enumerable map method is very similar to it. Both methods calls the code block once for each element in the object. The key difference between the two methods stop here.

After the each method runs the block for each element, it stops and then returns nil. The map method, on the other hand, stores the results that the code block return for each element into a new array and then return the new array after the method is finished. Using the map method can save you several lines of code if you’re making the each method store the results in a new array. It can also be useful in many other ways.

If you have any questions or what further clarification, please leave a message in the comment box below.

This blog has been initially published on tonymai.github.io.

Categories
Dev Bootcamp

Learn More Effectively – Maximize on Your Personal Thinking Style

The Concrete Sequential Thinker’s Journey

If you are unfamiliar with Anthony Gregorc’s Mind Styles Model, it is an organized way that aims to show how our minds think. The model breaks down the way we think into two perceptual qualities (concrete and abstract) and two ordering abilities (sequential and random), totaling to four different combinations of thinking styles:

  1. Concrete Sequential (CS)
  2. Abstract Random (AR)
  3. Abstract Sequential (AS)
  4. Concrete Random (CR)

My own personal thinking style is concrete sequential. Concrete sequential thinkers tend to be “based in reality. They process information in an ordered, sequential, linear way.” (If you want to find out what your thinking style is, you can take the test at The Learning Web.) It is important to note that no one is purely one style; everyone has a unique combination of each of these qualities. Furthermore, not one thinking style is better than another; they are just different. It is interesting to note that when I took the test two months again, my results were slightly different, so the way you think can change over time.

thinking-style

As a concrete sequential thinker, I process information in an “ordered, sequential, linear way.” I detect information and what is around me through my five senses (sight, touch, sound, taste, and smell). Concrete sequential thinkers tend to notice and recall details and facts-specific information easily (such as rules, formulas, and logic).

I plan on maximizing my thinking style while I am learning at DBC. As a concrete sequential thinker, I have very strong organizational skills. Since I absorb information through my physical senses, I plan to learn with a “hands on” approach. I will also provide myself with details and break down my projects into concrete, sequential steps that I can follow. Focusing on the strengths of my thinking style will allow me put what I need in place to learn more effectively. (To read more about the other types of thinking styles, check out this article from Boise State. You can also learn more about what works and what do not work for each thinking style in this article from SUNY Cortland.)

Again, I want to stress that just because you have one thinking style doesn’t mean that you can’t think in any other style. No one is purely one style and thinking/learning styles can change. Your brain is not static. It can grow and evolve if you allow it to, as shown by Carol Dweck‘s research on fixed and growth mindsets.

mindsetsIn short, a “fixed mindset” assumes that ones intelligence and abilities are inherited and cannot change. You are born with how much intelligence you have. These people will do things that they are good at to display their intelligence and avoid doing things that they may fail at. They avoid risks and challenges. A “growth mindset”, on the other hand, thrives on challenges and is not afraid of failure. They welcome failure and use it as a springboard for growth. They learn from their mistakes and use it to increase their knowledge. (To read more about fixed and growth mindsets, click here.)

Similarly to thinking style, your mindset isn’t one or the other either. You can have a growth mindset in some areas and a fixed mindset in other areas. I make an effort to always have a growth mindset on everything, but I still fall back into a fixed mindset sometimes (i.e. I will never learn how to swim…).

Nevertheless, keep this in mind and don’t let failure deter you. In fact, embrace it. If you have never failed at what you’re doing, then you aren’t challenging yourself enough. If one thing isn’t working, learn from your failures and try again another way. Some see failure as the opposite of success. I see it as necessary milestones on the way to success.

This blog has been initially published on tonymai.github.io.