Ikram Mihan

Ikram Mihan

1590316740

How to Fix Slow Code in Ruby

Knowing how to write fast code is useful, but insufficient without knowing how to fix slow code. In this post, we’ll discuss How to Fix Slow Code in Ruby

#ruby #ruby-on-rails #programming

What is GEEK

Buddha Community

How to Fix Slow Code in Ruby
Brain  Crist

Brain Crist

1594674000

Day 14 of 30 Ruby Coding Challenge - Fibonacci Sequence the Ruby Way

Day 14 of 30. We’re going to solve the famous Fibonacci sequence in a more Ruby Way, which will be much better (hopefully!) than the previous solution

Hey friends!

This is the blog post version of the Youtube video from the 30 Ruby Coding Challenges in 30 Days series

Fibonacci Sequence

It’s time to organize the kitchen and to get a better code design to solve the Fibonacci Sequence, which was the previous coding challenge:

We want to calculate the first N numbers in a Fibonacci sequence

This was the last coding solution:

Ruby

def fibonacci(count)

n1 = 0

  n2 = 1

sequence = [n1, n2]

  while count > 2

# sum of the previous 2 numbers

    n3 = n1 + n2

sequence.push(n3)

      # assigning the new numbers to calculate the next number in the sequence

n1 = n2

    n2 = n3

count = count - 1

  end

return sequence

end

puts fibonacci(8)

# 0 1 1 2 3 5 8 13
```

You can be honest, it's not that great.

## The Ruby Way to Solve the Fibonacci Problem

### **Step 1**

Ruby allows us to go from one number to another in a sequence like this:

Ruby

```
(0..10).each do |number|

end


In our example we want to avoid the count mutation (fancy name for change). We can do that by the following code:

Ruby

(0…count).each do |number|

end
```

That’s great because Ruby will **automatically iterate over the array**

### **Step 2**

A better way to store the number in the sequence would be:

Ruby

```
sequence << number if number <= 1

sequence << sequence[-1] + sequence[-2] if sequence.length >= 2


The complete code, a little bit leaner with a better strategy, would be:

Ruby

def fibonacci(count)

  sequence = []  

(0…count).each do |number|

    sequence << number if number <= 1

sequence << sequence[-1] + sequence[-2] if sequence.length >= 2

  end

sequence

end
```

Fantastic! Ruby deals with the problem really well!

#ruby #programming #coding #ruby on rails #algorithm #fibonacci #tutorial for beginners #algorithm analysis #coding basics #coding challenges

Tyrique  Littel

Tyrique Littel

1604008800

Static Code Analysis: What It Is? How to Use It?

Static code analysis refers to the technique of approximating the runtime behavior of a program. In other words, it is the process of predicting the output of a program without actually executing it.

Lately, however, the term “Static Code Analysis” is more commonly used to refer to one of the applications of this technique rather than the technique itself — program comprehension — understanding the program and detecting issues in it (anything from syntax errors to type mismatches, performance hogs likely bugs, security loopholes, etc.). This is the usage we’d be referring to throughout this post.

“The refinement of techniques for the prompt discovery of error serves as well as any other as a hallmark of what we mean by science.”

  • J. Robert Oppenheimer

Outline

We cover a lot of ground in this post. The aim is to build an understanding of static code analysis and to equip you with the basic theory, and the right tools so that you can write analyzers on your own.

We start our journey with laying down the essential parts of the pipeline which a compiler follows to understand what a piece of code does. We learn where to tap points in this pipeline to plug in our analyzers and extract meaningful information. In the latter half, we get our feet wet, and write four such static analyzers, completely from scratch, in Python.

Note that although the ideas here are discussed in light of Python, static code analyzers across all programming languages are carved out along similar lines. We chose Python because of the availability of an easy to use ast module, and wide adoption of the language itself.

How does it all work?

Before a computer can finally “understand” and execute a piece of code, it goes through a series of complicated transformations:

static analysis workflow

As you can see in the diagram (go ahead, zoom it!), the static analyzers feed on the output of these stages. To be able to better understand the static analysis techniques, let’s look at each of these steps in some more detail:

Scanning

The first thing that a compiler does when trying to understand a piece of code is to break it down into smaller chunks, also known as tokens. Tokens are akin to what words are in a language.

A token might consist of either a single character, like (, or literals (like integers, strings, e.g., 7Bob, etc.), or reserved keywords of that language (e.g, def in Python). Characters which do not contribute towards the semantics of a program, like trailing whitespace, comments, etc. are often discarded by the scanner.

Python provides the tokenize module in its standard library to let you play around with tokens:

Python

1

import io

2

import tokenize

3

4

code = b"color = input('Enter your favourite color: ')"

5

6

for token in tokenize.tokenize(io.BytesIO(code).readline):

7

    print(token)

Python

1

TokenInfo(type=62 (ENCODING),  string='utf-8')

2

TokenInfo(type=1  (NAME),      string='color')

3

TokenInfo(type=54 (OP),        string='=')

4

TokenInfo(type=1  (NAME),      string='input')

5

TokenInfo(type=54 (OP),        string='(')

6

TokenInfo(type=3  (STRING),    string="'Enter your favourite color: '")

7

TokenInfo(type=54 (OP),        string=')')

8

TokenInfo(type=4  (NEWLINE),   string='')

9

TokenInfo(type=0  (ENDMARKER), string='')

(Note that for the sake of readability, I’ve omitted a few columns from the result above — metadata like starting index, ending index, a copy of the line on which a token occurs, etc.)

#code quality #code review #static analysis #static code analysis #code analysis #static analysis tools #code review tips #static code analyzer #static code analysis tool #static analyzer

How Benchmarking Your Code Will Improve Your Ruby Skills

Learning to code is a path full of struggles, and learning Ruby isn’t the exception. But you’ll agree with me, that practice is the best way to learn and develop your skills.

Out there are plenty of sites to choose from where you can achieve this. But after n amount of solved challenges, you’ll start questioning your solutions.

You’ll start feeling, that is not enough to come up with an answer to the challenge. And you’ll be wondering if there is a better, faster, and less consuming memory approach.

If this is your case, if you have reached this stage, then you’re more than ready to begin benchmarking your code. And if you’re not, well, let me tell you that learning this will step up your game.

So, what is this “benchmarking” thing anyway?..

Benchmarking is the process of measuring the performance of something… in this case the performance of your code.

Benchmarking is the process of measuring the performance of something.

And that’s it, there is nothing more to add.

Yeah, I know what you’re thinking, that knowing the meaning doesn’t serve your purpose. But I’m positive that at least it will give you a broad idea.

With this in mind, the next question to answer is, “How benchmarking my code, will help me improve my coding skills?”.

This is an easy one. Benchmarking gives you knowledge, and knowledge is power. The better understanding of your code, the better code you’ll start programming. Is that simple!.

Benchmarking gives you knowledge, and knowledge is power.

Benchmarking gives you a simple view of how your code is performing. This view focuses on three main areas: elapsed timememory, and iterations per second.

  1. Elapsed time: is the amount of time your code takes to finish a task.
  2. Memory: is the allocated space in your drive that your code occupies to solve the task.
  3. Iterations per second: is the total number of repetitions your code can do the same task, over and over, in a second.

Ok, at this point I assume you have understood the basics of benchmarking. Hopefully, you are also saying to yourself - “Yeah, this is what I was missing, this will help me become a better programmer!”.

If you don’t think that way yet; I hope knowing how it works will do.

Now, how do we apply this?

Ruby makes it easy for us, as it already has a “Benchmarking” class, but we’ll complement it with two other ruby gems.

  1. Benchmarking-ips
  2. Benchmarking-memory

Before describing the steps to benchmark your code. I’m assuming you are using a linux/unix distribution, and have a working version of Ruby installed.

If you’re running some other OS like Windows, the next series of commands, probably, won’t work. But the benchmarking steps are going to be identical.

Let’s begin!.

a. The first step is to install this rubygems in your system; for that, you can use this command:

gem install benchmark-ips benchmark-memory

b. The second **step **is creating a ruby file, I’m going to call it “benchmarking_ruby.rb”, but you can name it in any way you want:

touch benchmarking_ruby.rb

b.1 Open the file with your preferred text editor. This file will contain three main sections:

- Section 1: Here we use require to include and grant our file access to the gems recently installed and the Ruby Benchmark Class. Doing so, will allow us to use the benchmark methods to measure our code performance.

require 'benchmark'
require 'benchmark/memory'
require 'benchmark/ips'

Section 2: We write the code that we want to benchmark.

def method_1(params)
    ## some code
end

def method_2(params)
    ## some code
end

Note:_ Benchmark works if you want to measure a single method but it’s best if you test at least two or more. Don’t worry too much about this right now, later on, I’ll show you an example and you’ll understand what I meant._

- Section 3: We set up the test.

This part is tricky but not complicated. Look at the image below and try to identify what’s happening.

def benchmark(params)
    Benchmark.bmbm do |x|
        x.report ("Method One") { method_1(params) }
        x.report ("Method Two") { method_2(params) }
    end

    Benchmark.memory do |x|
        x.report ("Method One") { method_1(params) }
        x.report ("Method Two") { method_2(params) }
        x.compare!
    end

    Benchmark.ips do |x|
        x.report ("Method One") { method_1(params) }
        x.report ("Method Two") { method_2(params) }
        x.compare!
    end
end

benchmark(params)

We are declaring a method called “benchmark” that accepts some parameters (or arguments).

def benchmark(params)
    ...
end

#ruby #benchmark #learn-to-code-ruby #rubygems #code-performance #how-to-benchmark-ruby #benchmark-ips #benchmark-memory

Agnes  Sauer

Agnes Sauer

1595544900

Day 18 of 30 Ruby Coding Challenge - Finding the Missing Number Game

This is the blog post version of the

Let’s go straight to the point

Coding Challenge

Create a function that takes an array of numbers between 1 and 10 (excluding one number) and returns the missing number.

A few points:

  • The array of numbers will be unsorted (not in order).
  • Only one number will be missing.

Examples

Ruby

1

find_missing_num([1, 2, 3, 4, 6, 7, 8, 9, 10]) ➞ 5

2

3

find_missing_num([7, 2, 3, 6, 5, 9, 1, 4, 8]) ➞ 10

4

5

find_missing_num([10, 5, 1, 2, 4, 6, 8, 3, 9]) ➞ 7

Pretty simple, isn’t it?

Algorithm in Ruby

Let’s break the algorithm down to a few small steps:

Step 1

We need to go through a list of items (an array), going from 1 to 10.

Ruby

1

def find_missing_num(array)

2

  [1, 2, 3, 4, 5, 6, 7, 8, 9, 10].each do |item|

3

    end

4

end

5

6

array = [1, 2, 3, 4, 6, 7, 8, 9, 10]

7

find_missing_num(array)

Ruby provides us a really better way to do this:

Ruby

1

def find_missing_num(array)

2

  (1..10).each do |item|

3

    end

4

end

5

6

array = [1, 2, 3, 4, 6, 7, 8, 9, 10]

7

find_missing_num(array)

Step 2

We’re going to compare each number (from 1 to 10) with the numbers in the given array.

Ruby

1

def find_missing_num(array)

2

  (1..10).each do |item|

3

    array.each do |number|

4

      if item == number

5

        break # breaking the execution

6

      end      

7

    end

8

  end

9

end

10

11

array = [1, 2, 3, 4, 6, 7, 8, 9, 10]

12

find_missing_num(array)

We break the execution once if find the desired number because we don’t need to continue looking for the number

Step 3

Because we want to return the number that wasn’t found in the array, I’m going to create a local variable to indicate that.

Ruby

1

def find_missing_num(array)

2

  (1..10).each do |item|

3

    found = false

4

    array.each do |number|

5

      if item == number

6

        found = true

7

        break

8

      end      

9

    end

10

    if found = false

11

      return item

12

    end

13

  end

14

end

15

16

array = [1, 2, 3, 4, 6, 7, 8, 9, 10]

17

find_missing_num(array)

That’s it!

I know, that’s not beautiful but it works : )

Do you have a better/different version? Drop that in the comments and bring more healthy discussions :)

Thanks for the visit and in the next coding challenge we’re going to explore a more decent way to solve this puzzle, see you there!

Don’t forget to come by and say hi!

Courses Twitter Youtube Instagram Linkedin GitHub

#ruby #programming #code #algorithms #coding #game #ruby on rails #arrays

Samanta  Moore

Samanta Moore

1621137960

Guidelines for Java Code Reviews

Get a jump-start on your next code review session with this list.

Having another pair of eyes scan your code is always useful and helps you spot mistakes before you break production. You need not be an expert to review someone’s code. Some experience with the programming language and a review checklist should help you get started. We’ve put together a list of things you should keep in mind when you’re reviewing Java code. Read on!

1. Follow Java Code Conventions

2. Replace Imperative Code With Lambdas and Streams

3. Beware of the NullPointerException

4. Directly Assigning References From Client Code to a Field

5. Handle Exceptions With Care

#java #code quality #java tutorial #code analysis #code reviews #code review tips #code analysis tools #java tutorial for beginners #java code review