Remove a exclamation mark from the end of string

From codewars.com by Edxael  (that’s me)

Description:

  • Remove a exclamation mark from the end of string. For a beginner kata, you can assume that the input data is always a string, no need to verify it.
  • Examples

My solution:

Note:  The following code is not written by me, it was created by another user of codewars.com it belongs to the user: “cyberplanner” enjoy.

 

 

Category: Ruby Examples | Comments Off on Remove a exclamation mark from the end of string

Two to One

From codewars.com by Edxael  (that’s me)

Instructions:  Take 2 strings s1 and s2 including only letters from ato z. Return a new sorted string, the longest possible, containing distinct letters, – each taken only once – coming from s1 or s2.

Examples:

My solution:

Note:  The following code is not written by me, it was created by another user of codewars.com it belongs to the user: “Beast” enjoy.

 

Category: Ruby Examples | Comments Off on Two to One

Ones and Zeros

From codewars.com by Edxael  (that’s me)

Instructions: Given an array of one’s and zero’s convert the equivalent binary value to an integer.

Eg: [0, 0, 0, 1] is treated as 0001 which is the binary representation of 1

Examples:

my solution:

Note:  The following code is not written by me, it was created by another user of codewars.com it belongs to the user: “basilekoko” enjoy.

Note:  The following code is not written by me, it was created by another user of codewars.com it belongs to the user: “dzNET” enjoy.

 

 

Category: Ruby Examples | Comments Off on Ones and Zeros

Which are in?

From codewars.com by Edxael  (that’s me)

Given two arrays of strings a1 and a2 return a sorted array r in lexicographical order of the strings of a1 which are substrings of strings of a2.

Example 1:

a1 = ["arp", "live", "strong"]

a2 = ["lively", "alive", "harp", "sharp", "armstrong"]

returns ["arp", "live", "strong"]

Example 2:

a1 = ["tarp", "mice", "bull"]

a2 = ["lively", "alive", "harp", "sharp", "armstrong"]

returns []

Notes:

Arrays are written in “general” notation. See “Your Test Cases” for examples in your language.

Beware: r must be without duplicates.

Note:  The following code is not written by me, it was created by another user of codewars.com it belongs to the user: “colbydauph” enjoy.

 

Category: Ruby Examples | Comments Off on Which are in?

Who likes it?

From codewars.com by Edxael  (that’s me)

You probably know the “like” system from Facebook and other pages. People can “like” blog posts, pictures or other items. We want to create the text that should be displayed next to such an item.

Implement a function likes :: [String] -> String, which must take in input array, containing the names of people who like an item. It must return the display text as shown in the examples:

 

For more than 4 names, the number in and 2 others simply increases.

— My Code —

Note:  The following code is not written by me, it was created by another user of codewars.com it belongs to the user: “surendraa” enjoy.

 

Category: Ruby Examples | Comments Off on Who likes it?

Create Phone Number

From codewars.com by Edxael  (that’s me)

Write a function that accepts an array of 10 integers (between 0 and 9), that returns a string of those numbers in the form of a phone number.

Example:

The returned format must be correct in order to complete this challenge.
Don’t forget the space after the closing parentheses!

— My Code —

Note:

The following code is not written by me, it was created by another user of codewars.com it belongs to the user: “Jwashton” enjoy it.

 

Category: Ruby Examples | Comments Off on Create Phone Number

Write Number in Expanded Form

You will be given a number and you will need to return it as a string in Expanded Form. For example:

  • expanded_form(12); # Should return ’10 + 2′
  • expanded_form(42); # Should return ’40 + 2′
  • expanded_form(70304); # Should return ‘70000 + 300 + 4

 

Category: Ruby Examples | Comments Off on Write Number in Expanded Form

Vampire Numbers

Instructions

6 * 21 = 126 # 6 and 21 would be valid ‘fangs’ for a vampire number as the # digits 6, 1, and 2 are present in both the product and multiplicands

10 * 11 = 110 # 110 is not a vampire number since there are three 1’s in the # multiplicands, but only two 1’s in the product

 

Category: Daily, Ruby Examples | Comments Off on Vampire Numbers

Special Methods Examples

 

Here you will be able to find some examples of methods, that might come handy when in need, those are simple examples that will help to understand how to use the method. they are not in any specific order, so I recommend you to just do quick review to see if you find something that can help.


“.times” Block with curly braces

Using the Iteration as a parameter on a variable

“.upto”    Start with 1 instead of 0

“.cycle”

this will execute the instruction on the block “.cycle(x)” where x is equal to the times that the cycle will run.

“.each” <– Can’t Catch

Will execute the block and return the answer for each element without modifying the “Array”

“.collect”

This will return an Array with the values of the block, without modifying the original “Array”

“.Map”

Here we have another method that accomplish the same thing as in the previous example

“.detect”

This one will do exactly what it says, but as soon it finds one value that fulfills the conditional in the block will return that value and skip the rest of the array, even if they are true too.

“.select”

This method will select all the values that fulfills the conditional, and return them, w/m orig Arr.

“.reject”

Opposite to “.select” this method will return elements == false, w/o m orig Arr

“.find”

Will return the FIRST of occurrence that the block is “True”, w/o modifying original Array

“.find_all”

Will return an Array with values when the Block was True, w/o modifying original Array.

“.inject”

This is a fun one and have several applications, here you have two parameters, one will be the accumulator that in this case we name “acc”, but it can be name whatever you want. and “n” this is the one that will iterate each of the elements of the array, Hash, etc.

in the following example we will add all the values together.

“.inject(x)”

here you can also set up acc with a initial value, in the next example we will give it the value of 10 but we will leave all the other things the same so the answer should be 16.

you can return arrays too, in the following example we will initialize the acc as an array by .inject([]) and then in the block we will shovel n*n this means that each number will be multiply by it self and then shovel into the array.

“.reduce”

one use of “.reduce is to sum the elements in an Array” or Multiply them.

“.all?”

This will evaluate all the elements and return true or false depending if all elements fulfills the rules of the method. example:

“.any?”

This will evaluate all the elements and if one or more fulfills the rules of the block will return “true” if none then will return “false”

“.drop”

This will drop the firs x elements

“.drop_while”

This one will delete elements from left to right until one element do no fulfill the block, regardless if other elements on should be drooped.

“.each_slice”

This will slice the array momentarily to mini arrays of x number of elements. w/mod orig arr.

“.group_by”

This one will return a hash where the keys are the product of the computations executed on the block, and the value is an array with the values that have that product.

“.include”

This is not a block but it seems to be useful, basically it will review all the array and return yes if the indicated value is part of the the values on the array.

“.max”

here we have an example where we create an array of words, then we print the max when max means the highest indice, then we print the max but we modify it with a block that will chose the the max in terms of highest number of characters.

here is the same example but modify to provide the two longest strings.

here is one variation here we will find the longest string

“.min”

Its name says it all

“.minmax”

Another way to get them by the length is

“.charts”

will create an array from a string

“.count”

it can also count occurrences in a “String”

“benchmark” —  “:bsearch”

“.index(x)”

“.gsub”

Returns a copy of str with the all the occurrences of a patter substituted

It also can add extra characters or spaces in between

“.flatten”

This will take a TWO dimensional array and flatten it to a ONE dimensional array.

It can also regulate what dimensions to flatten, the next example is a 3rd dimensional Array where we flatten only one of the two sub-dimensions.

 

 

line

 

Category: Ruby | Comments Off on Special Methods Examples

Ruby Shorcuts

Here I will post some of the shor-cuts that I find while learning, some times you come across a cool way to do a little trick, you know that is valuable information, you just don’t need it now, well that happen to me in the pas and latter when writing some program in that moment that you read an article in how to solve this specific problem, but you do not remember where to find that information.

Well this is the place where I will put some notes for when I find something that falls on that category. some of this things for you might seem very simple and basic stuff, and that might be true, but I’m learning from the beginning. so here are the notes.

 


Multinline of Comments

Yes I use # alot and is just fine, it wont hurt to know there is another way.

Find Smallest & Largest

.

Category: Ruby | Comments Off on Ruby Shorcuts

Ruby Calisthenics

Here is some practice on the Prep-Work of the Viking Code School. in the following section we will be developing the solution to some challenges located on the Prep-Work, this will be fun, well with no more delay lest dive on this exercises.

1.Power

Write a method power which takes two integers (base and exponent) and returns the base raised to the power of exponent. Do not use Ruby’s **operator for this!

This code works with Integers and Negative values. unfortunately I need more time to make it to work with decimals, but coming soon.


2.Factorial

Write a method factorial which takes a number and returns the product of every number up to the current number multiplied together.


3. Uniques

Write a method uniques which takes an array of items and returns the array without any duplicates. Don’t use Ruby’s uniq method!

The following solution is Dynamic and Interactive, you will be prompted to provide: size of the array, maximum value, and minimum value, whit this information the software will create and populate an array with the provided specifications, then it will print it so you can see it. after that it will delete all duplicates and presented only the UNIQUE values in an organize order.

Because things happen, in case that you mix the Maximun and Minimum values it will catch it and fix it.


4. Combinations

Write a method combinations which takes two arrays of strings and returns an array with all of the combinations of the items in them, listing the first items first.

 


5. Primes

Write a method is_prime? which takes in a number and returns true if it is a prime number.

In this case, “Huston we got a problem”  basically there is NOT a test that would pinpoint Prime Numbers with a 100% exactitude, no matter how fancy the method you choose. for this reason I create a very basic way to find out if a number is prime, Using a library call prime.

 


6. Rectangle Overlap

Write a method overlap which takes two rectangles defined by the coordinates of their corners, e.g. [[0,0],[3,3]] and [[1,1],[4,6]], and determines whether they overlap. You can assume all coordinates are positive integers.

It doesn’t count as overlapping if their edges touch but they do not otherwise overwrite each other. As expressed by a sixth grade student:


7. The Counting Game

10 friends are sitting in a circle around a table and decide to play a new game. In it, they count up through the numbers from 1 to 100. The first person says “1”, the second says “2” and so on… but with a few catches:

  • Whenever the number is divisible by 7, they switch directions. So person 6 will say “6”, person 7 will say “7”, then person 6 again will say “8”.
  • Whenever the number is divisible by 11, they skip the next person for the following number. For instance, if person 3 says “33”, person 5 will say “34” instead (person 4 gets skipped).

 

 

 

Category: Ruby Examples | Comments Off on Ruby Calisthenics

Project Euler

Multiples of 3 and 5

If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.

Find the sum of all the multiples of 3 or 5 below 1000.


Even Fibonacci numbers

Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:

1, 2, 3, 5, 8, 13, 21, 34, 55, 89, …

By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.

this was fun, my first attempt was no successful, basically I create a code that would work for a small number of the series, and it work but when I plug the 4,000,000 well it kill the console, literally after few minutes it returns “kill” I guess that was the brute force approach and I pay dearly, the following code is the brute force and DO NOT plug it on your computer or you will pay for it, but it would be nice if you see it.

well that is what I got for creating arrays with millions of entries, jajaja,

now the second attempt, this time I had to do some research and took me time, but after some failures the following code is the one that work


Largest prime factor

The prime factors of 13195 are 5, 7, 13 and 29.

What is the largest prime factor of the number 600851475143 ?

This is one of those programs that need to be improve because I don’t think the code is efficient, it works, gets the job done but I will re-think this one latter and come with a better solution, in the mean time here is a working solution.


Largest palindrome product

A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.

Find the largest palindrome made from the product of two 3-digit numbers.

 

Category: Ruby Examples | Comments Off on Project Euler

Writing Methods

How many things should a method ideally do?

Just ONE


What types of things should a method modify?

Any type of data.


What should you name a method?

Method names in Ruby may contain upper-case and lower-case letters, numbers, underscores _ and the punctation signs !, ?, =.

A method name can’t begin with a number, and the characters !, ? and = can only appear at the end.

Non-ASCII characters can be used in a method name, but this can lead to very confusing situations and should not be common practice.


What does self mean?

This means that the intended code will apply only to the current instance of the class,


What do you need to do to create your own Ruby script file?

a computer that can save a text file with a .rb extension, basically any computer with the most basic text editor.


How would you run a Ruby script from the command line?

First you need to make sure that you have Ruby enviroment and requested gems install and updated.

Go (cd ….) to the directory where the .rb file is located.

Then type: ruby name_of_file.rb and hit enter.

Category: Daily | Comments Off on Writing Methods

Enumerable

Why are modules useful?

As its name explain it it a separate and individual part of the code, and here are three of the reasons why it is useful:

  • Because you can group together: Methods, Classes, and Constants. In a single module
  • It prevent a name space and prevent name clashes.
  • Modules implement the mixin facility.

What does #each do?

Calls the given block once for each element on it self. One example is to print the list of countries that I travel to:


What does #each return?

As you can see on the example above, it will pass the element as a parameter.


What does #map do?

This method takes an enumerable object and a block, and runs the block for each element, the original object is not change unless you use .map! for a better grasp of what this means see the code below.


What does #map return?

As you can see on the example, this will return the product of each element executed by the code on the block.


What does #select do? & What does #select return?

It takes an array and processed in a block with specific filters or rules coded on a block, it will return a new array containing all elements of the previous array for which the given block returns are true.

Now en English and with one example, Imagine that you have an array with number from 1..10 and you want to get those that are divisible by 2, in this example we will use the method .select to do just that.


What is the difference between #each #map and #select?

They are tools that do different things, when given the same array:

.each : will return each element of the array

.map : will process each element with some coded instructions and return the product.

.select : will filter each element to return those  that pass the coded requirements.

Category: Daily | Comments Off on Enumerable

Blocks

How is a block like a function?

The way that I see a block as a function is because both can be call and you can pas parameters to both.


How is a block different from a function?

One of the major differences that I see is that you can pass a block to a block but you can not pass a function to a function.


What are the two ways to declare a block?

The Ruby standard is to use braces for single-line blocks and do..end for multi-line blocks.


How do you return data from a block?

Ruby blocks will return the last line by default, so make sure that you put on the last line what you want to return.


What happens if you include a return statement in a block?

It will return that line instead of the last line


Why would you use a block instead of just creating a method?

Because blocks can be pass to other blocks and to other methods, and methods no


What does yield do?

Will pause the method and execute the code on the block, after that it will return to the method


How do you pass arguments to a block from within a method?

putting the parameters that you want to pass between pipes.


 

 

 

Category: Daily | Comments Off on Blocks

Iteration

What are the two ways to denote a block of code?

The standard in Ruby would be to use Braces for single-line blocks and do..end for multi-line blocks. keep in mind that the braces syntax has a higher precedence that the do..end syntax, here are some examples:

Using the do..end

but remember that you can pass parameters, so in the following example we will pass a parameter.

I will be honest with you, this do not look that interesting, because we can do the same thing with methods, but the problem with methods is that you can not pass a method to another method, but you can pass a block to another block, another use would be if you need to open a file write information and close the file, we will use this file case on the next example.

 

–  –  –  –  –  –  –  –  –  –  –  –  –  –  –  –  –  –  –  –  –  –  –  –  –  –  – – –  –  –  –  –  –  –

What is an index variable?

This are used on loops, as we know a loop is a chunk of code that will run a number of times until some conditions are met,  in most of the cases we use a variable to keep track in what run of the loop you are and the loop will stop when the variable is equal to the set value. in the example we have one taxi that can sit 5 passengers,  so we will seat 5, and then we will tell to the other passengers to wait for the next taxi.

–  –  –  –  –  –  –  –  –  –  –  –  –  –  –  –  –  –  –  –  –  –  –  –  –  –  – – –  –  –  –  –  –  –

How do you print out each item of a simple array [1,3,5,7] with:
while?

for?

#each?

#times?

–  –  –  –  –  –  –  –  –  –  –  –  –  –  –  –  –  –  –  –  –  –  –  –  –  –  – – –  –  –  –  –  –  –

What’s the difference between while and until?

While will run as long as the condition continues to be True, Until in the other side is false and will stop the loop when the condition became True.

–  –  –  –  –  –  –  –  –  –  –  –  –  –  –  –  –  –  –  –  –  –  –  –  –  –  – – –  –  –  –  –  –  –

How do you stop a loop?

The loop will stop when the condition is met. also you can stop it using break.

–  –  –  –  –  –  –  –  –  –  –  –  –  –  –  –  –  –  –  –  –  –  –  –  –  –  – – –  –  –  –  –  –  –

How do you skip to the next iteration of a loop?

Here we need to use an example, the following loop will print numbers from 1 to 10 but if the number is even, i don’t want to run the rest of the code of the loop, instead I want to skip to the next iteration of the loop.

–  –  –  –  –  –  –  –  –  –  –  –  –  –  –  –  –  –  –  –  –  –  –  –  –  –  – – –  –  –  –  –  –  –

How would you start the loop over again?

you have two options use the redo and retry, but be careful you can end up with an infinite loop.

–  –  –  –  –  –  –  –  –  –  –  –  –  –  –  –  –  –  –  –  –  –  –  –  –  –  – – –  –  –  –  –  –  –

What are the (basic) differences between situations when you would use while vs #times vs #each?

this are the answers that come to my head right now, if in the future I might expand on it:

While: I would use this one as long as the condition is false, and when the condition is true, then it will end the loop.

Times: I would use this when I know beforehand how many times I will need to run the code.

Each: I would use this when I know that the number of times is stored on an array, variable, ect

–  –  –  –  –  –  –  –  –  –  –  –  –  –  –  –  –  –  –  –  –  –  –  –  –  –  – – –  –  –  –  –  –  –

What does nesting loops mean and when would you use

Nesting loop means that you put a loop whiting a loop, and you use it when you need a loop whiting a loop. I know this answer is kind of stupid, jajaja, but let me give you an example, in the prep work we have one code that is the logic game with the following rules.

10 friends are sitting in a circle around a table and decide to play a new game. In it, they count up through the numbers from 1 to 100. The first person says “1”, the second says “2” and so on… but with a few catches:

  • Whenever the number is divisible by 7, they switch directions. So person 6 will say “6”, person 7 will say “7”, then person 6 again will say “8”.
  • Whenever the number is divisible by 11, they skip the next person.

Your job is to pseudocode a program which will determine which player says the number 100.

to do this I used two while’s nested whiting a while. see the code below.

To see all the outputs line by line, Un-Coment lines: 26, 50, 73. and then run the code again.


how to use UNLESS

 

Category: Daily | Comments Off on Iteration

Conditionals and Flow Control

What is a “boolean”?

A boolena is a value that can be True or False, this is a great tool to find out if things are or are not.

– – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – –

What are “Truthy” values?

Mmmm as we know booleans are True or false. but sometimes we want to use a non-boolean value (integers, strings, arrays, etc.) in a boolean context, because programing languages like “RUBY” are software too, that means the people who built Ruby had to decide what is truthy, and what is falsey, in ruby only false and nill are false, everything else is truthy (even “0” is truthy)

here is a simple example

– – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – –

Are nil, 0, “0”, “”, 1, [], {} and -1 considered true or false?

well we will do this the hard way, that  meas we will test each one.

– – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – –

When do you use eleseif?

you use this when you have a second condition in case that the first was false. (there is no limit in how many elesif you can use) so it can work for 3rd and up conditions, lest think of one example.

the next program, ask you for what place did you cross the finish line, if you put 1 you won Gold, if you put 2 you won Silver, if you put 3 you won Bronze, any other number will tell you thanks for your participation.

I did not include the output because, it depends on the input that you provide, please run this code on your terminal to see how it works.

– – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – –

When do you use unless?

this one executes the code when the conditional is false, or in other words, all values will be true but the one that you chose, and here an example.

This sofware ask what is your name, whatever the name is it will tell “Welcome to Hogwarts” but if you type “voldemort” you will will get the Expecto Patronus spell.

– – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – –

What do || and && and ! do?

This are logical operators, “||” means “or” this means that you have two (or more) options that will pass the test. In the example on company is looking for programmers, but in order to be hire you need to have a bachelor degree or work in programming before. see example below