1. Deep copy When you copy an object that contains other objects, like an Array, only a reference to these objects is copied. You can see that in action here:
1 2 3 |
food = %w( bread milk orange ) food.map(&:object_id) # [35401044, 35401020, 35400996] food.clone.map(&:object_id) # [35401044, 35401020, 35400996] |
Using the Marshal class, which is normally used for serialization, you can create a ‘deep copy’ of an object.
1 2 3 |
def deep_copy(obj) Marshal.load(Marshal.dump(obj)) end |
The results:
1 |
deep_copy(food).map(&:object_id) # [42975648, 42975624, 42975612] |
2. […]
Understanding Blocks Blocks are very prevalent in Ruby, you can think of them as little anonymous functions that can be passed into methods. Blocks are enclosed in a do / end statement or between brackets {}, and they can have multiple arguments. The argument names are defined between two pipe | characters. If you have […]
Arrays are a fundamental data structure that stores data in memory. In Ruby you can store anything in an array, from strings to integers and even other arrays. The elements in an array are accessed using their index, which starts at 0. This is what an array containing the words “cat”, “dog” and “tiger” would […]
If you want to do anything related with time you probably want to use some sort of class that can store and work with this type of data. In this article you will learn what time-related classes and methods are available in Ruby and how to use them. The Time Class To manage time in […]
If you aren’t familiar with the term, refactoring is the act of improving the quality of code without changing what it does. This will make your code a lot easier to work with. In this post you will learn some common refactoring techniques, let’s get started! Extract Method One of the most common refactorings is […]
Whenever you need to use some if / elsif statements you could consider using a Ruby case statement instead. In this post, you will learn a few different use cases and how it all really works under the hood. Note: In other programming languages this is known as a switch statement. Ruby Case & Ranges […]
APIs are great because they let you interact with other applications, but they can be a bit intimidating if you never used one before. In this post I will show you how to get started using your favorite APIs with Ruby. A simple API To use an API you will need some form of HTTP […]
What would you do if you are given a big collection of text and you want to extract some meaning out of it? A good start is to break up your text into n-grams. In the fields of computational linguistics and probability, an n-gram is a contiguous sequence of n items from a given sequence […]
© 2016 Black Bytes. All rights reserved.
Delicately crafted using Franz Josef theme and WordPress.