Loading
Abi Travers

My Blog. Full Stack Software Engineer. Ex-Growth Hacker.

Talking Through a Logical Ruby Challenge

As part of the Makers Academy  pre-course week 2 we have been tasked with working through the Ruby-Kickstarter github tutorials by Josh Cheek.

I decided to go through my thought process on one of the challenges I got stuck on, 1:6, in the hope that this may help me discover the solution. This post is about how I went about trying to understand the challenge and what I am still confused about. I have ordered this post as the way I looked at the information, worked through it in a lineal time format.

So hold tight as we ride through the waves of my mind … and apologizes if i stray off on a visual tangent ..

 

Question Asked:

 

You'll get a string and a boolean.

When the boolean is true, return a new string containing all the odd characters.

When the boolean is false, return a new string containing all the even characters.

If you have no idea where to begin, remember to check out the cheatsheets for string and logic/control

# odds_and_evens("abcdefg",true)    # => "bdf"

# odds_and_evens("abcdefg",false)   # => "aceg"

 

So two things that are seemingly unrelated are now bound together by a method I am to create …

My solution:

def odds_and_evens(string, return_odds)

  if return_odds

   string.size.times do |n|

   next if n % 2 == 0

   print 'n'

  end

   else

    string.size.times do |n|

    next if n % 2 != 0

   print 'n'

  end

end




odds_and_evens("abcdefg",true)

odds_and_evens("abcdefg",false)

Initial Issues:

  1. I don’t understand why this does not ‘print’ the answer to the screen when I call the method odds_and_evens(“abcdefg”,true).
  2. When I run the rake test on the file I get the following error messages.:

 

syntax error, unexpected end-of-input, expecting keyword_end

rake aborted!

Command failed with status (1):

 

The Given Solution:

 

def odds_and_evens(string, return_odds)

to_return = ""

string.size.times do |index|

next if return_odds && index.even?

next if !return_odds && index.odd?

to_return << string[index]

end

to_return

end

 

My thought process, the steps it went through:

We want to design a method which takes two arguments, one is a string of characters the other is a true or false statement.

The first step is therefore to create this method name it ‘odds_and_evens’ and pass it two arguments ‘string’ and ‘return_odds’.

def odds_and_evens(string, return_odds)

We want this method to return the string, given to it, in an altered way.

We need some mechanism to return the string at the end.

We will have to split this string into an array of it’s characters in order to count which index number each character sits at. So we need something which converts it back to a string.

By putting a variable set as ‘to_retrun’ then assigning it a value of an empty string we can then push the characters of the original string which has passed through our if argument, back into it.

to_return = ""
to_return << string[index]

We want it to split up this string into its characters. So the string is now an array of it’s characters.

 

The index number of the character in a string is what will determine if it is odd or even. Index numbering starts at 0. All the characters with an odd index number are add, all the characters with an even index number are even.

The method .size returns the character length of a string.

string.size

.times do is a loop. What this does is say ‘for’ a certain amount of times (we have assigned this number with the .size method) ‘do’ the following block of code.

string.size.times do |index|

What I am still confused about here:

Does .times do or .size split a string into an array? I Have tried to look for this answer but cannot find it.

Potential answer:

We not need to split the string into its characters, do we simply need to assign a number to each character in the string depending on it’s place and act on those numbers … drawing the string back according to those numbers.

We need to do something different to the string depending on weather the returns_odd variable, is true or false.

We need an if statement which looks at the returns_odd varaibale and the split string. We need a Boolean here.

&& index.even?
&& index.odd?

If it is true then we need to return only the characters at the odd index number.

If returns_odd is not an object, i.e. it is false, we need to return only the characters at the even index numbering.

The string is passed through the loop block of code.

string.size.times do |index|

next if return_odds && index.even?

next if !return_odds && index.odd?

The name  ‘index’ is given to the block of code as a placeholder for every character in the string. So on the first loop around the code it represents the character at index 0, then on the next, the character at index 1 and so on.

The block of code then assesses if the character which is now the ‘index’ has an odd or even index number.

 

I need to go through the loop again:

When the string is split up into its characters, an index number is assigned to each character according to it’s original string, starting with 0:

string.size.times do |index|

next if return_odds && index.even?

next if !return_odds && index.odd?

 

So for size(the arrays’ length or size) number of times each character is assigned to the ‘index’ placeholder.

The character at the ‘index’ placeholder is then put through the argument;

Is the returns_odd object true? If so pass over all those characters whose index number is even.

If retruns_odd is not an object, give me back all the characters which appear at an even index number. Do not give me back any characters which have been assigned an odd index number.

At the moment these characters are still an index number.

We need to return the string which has been through the the argument.

We push this new ‘string’  into the empty string variable we set at the beginning.

to_return << string[index]

The string is now an array which has the elements assigned to ‘index’. As it is displayed as string[index].

 

Walking through this solution in depth, explaining the coding solution to myself in english has allowed me to really understand what is going on with it. As a beginner looking at a seemingly difficult logical problem can seem very daunting if you don’t understand what it is saying. I highly recommend talking, (or writing), yourself through some code. It helped to understand the logic and hopefully apply it in future. Ruby seems like a game of cards, or musical instrument, the more you play the better you get but this only comes with practice …

(Apologize to those who are simply trying to learn ruby and are not interested in the shameless plug of my photographs).

 

Learning Ruby The Hard Way | How I Beat the Un-stoppable Error Messages

Trouble shooting exercise 25 of learning ruby the hard way by zed

I have enrolled at the intense computer programming bootcamp, the Maker Academy, next month. To get a head start I thought I would work through Zed Shaw’s Learn Ruby the Hard Way book.

Exercise 25 seems to be testing my problem solving skills so I thought I would write a post documenting how I worked out then fixed my error messages. This post is aimed at newbies to the programming world as I imagine it is very basic things which I am getting wrong.

First Script – The Start of the Problem 

This was my first attempt at writing exercise 25’s script in my editor:

exercise 25 of Learn ruby the hard way by zed shaw error messages

 

 

 

 

 

 

 

 

 

 

 

 

When I ran this in the terminal I got the following error message:

ex25.rb:2:in `<main>’: undefined local variable or method `ex25′ for main:Object (NameError)

The first thing I did was google the error message.

Solving the Error Message with Google 

I found an answer on Stackoverflow. It told me I was accidentally typing Alt + Space on my Mac, therefore creating non-breaking space. That this is considered by Ruby as part of the variable name as opposed to the whitespace it was intended to be.

It gave two solutions to this problem:

1.  Remapping Alt + Space to space to stop this typo occurring again.

2. Highlighting invisible characters in text editor to immediately realise the typos.

 

The preference seemed to be for solution 2  so I thought I would try this way first. It seemed the most simple and quick to fix. I wanted to rule out the off-the-shelf issue to my broken code.

Highlight invisible characters in my text editor – Part 1

Next I googled how to highlight invisible characters with my text editor, Sublime Text editor 2.

Turns out this is supposed to be a default feature of my text editor. Every time I highlight text I am supposed to be able to see little white dots like the image below (look close they are there in the empty spaces):

how to highlight invisible characters with Sublime Text editor 2

 

 

 

 

 

 

 

 

So I highlighted the text and nothing happened:

textselected in sublime text editor 2 learn ruby the hard way ex25

 

I decided to park the problem of ‘non-breaking’ spaces here for now and try and solve my error message an easier way. I am relatively new to coding so the next solution for finding ‘non-breaking’ spaces, fixing the preferences or default key assignments in Sublime Text editor, did not seem like the easiest way to solve my problem.

Googling the exercise itself

The next thing I did was google ‘Ex25 learn Ruby the hard way’ to see if anyone else was having the same issues as I was. I found a blog with the exercise typed out. I compared our files word for word on my screen.

I could not SEE any difference between our files (indicating the hidden non-breaking spaces may be what is causing my error).

However I needed to rule out the idea there was a typo I couldn’t spot somewhere, so I typed out the whole file again. Figuring this was a quicker way to get to the solution.

My second file worked when I ran it in the terminal. No error message.

Here is the second file:

Script for exercise 25 learn ruby the hard way. no errors

I was intrigued where I went wrong with the first file still, so I compared them line for line.

Comparing the working script to the one with an error message

Compared them on my screen and noticed two differences which I fixed one at a time.

exercise 25 of learn ruby hard way. Errors

1.  When the earlier functions were called in later ones eg.

def ex25.print_first_and_last(sentence)

words = ex25.break_word ..

The ex25.break_word function looked like it had not been recognised in the error script (one on the right) whereas the Ex25. appeared blue in the other script (left).

The most obvious reason I could come up with  was that the ‘e’ wasn’t capitalised. So I changed all Ex25’s in the broken script to a capitalised e.

exercise 25 of learning ruby the hard way, broken script

 

I ran the script but still got the same error message:

ex25.rb:2:in `<main>’: undefined local variable or method `ex25' for main:Object (NameError)
2. The next easy fix I noticed was the file name and the function name in the broken script were the same but in my new script I had named the file EX25b.rb.

Maybe it was this difference in naming which was responsible for the error?

Nope ..

ex25.rb:2:in `<main>’: undefined local variable or method `ex25' for main:Object (NameError)

Had I read the whole of the exercise in Learning Ruby the Hard Way I would have seen this wasn’t the answer:

“The Ex25 module doesn’t have to be in a file named ex25.rb. Try putting it in a new file with a random name then import that file and see how you still have Ex25 available.”

So I decided to go back to the first solution, non-breaking space as I had now exhausted the easy options and couldn’t for the life of me  see any difference between the error or the correct script.

Highlight invisible characters in my text editor- Part 2 

I read how to do this here.

1.  Open the ‘preferences’ within Sublime text editor & select ‘key bindings’.

Preferences, key bindings within Sublime text editor 2

 

 

 

 

 

 

2.   Insert into the left side, the ‘user’ tab the following code:

{

"keys": ["alt+space"],
"command": "insert_snippet",
"args": {"contents": " "}

}


User tab of key binding sublime text editor

code inserted sublime text editor changing key bindings to show up alt + space bar on macs

 

 

 

 

 

 

 

 

 

 

 

 

 

 

3.   Saved then re-opened the original (broken 🙁 ) file.

Sure enough there was the accidental Alt and space bar non-breaking space:

Alt and Space bar error on a mac and sublime editor 2

 

 

HALLELUJAH .. I thought.. I have finally fixed my old script…….

I ran it again and I STILL had the same error message!

Here is where I probably should have thought:

“I got it correct once and managed to work through the exercise and complete it. I will just call it a day and not worry about the file which is returning an error message”.

But I am too curious / stubborn to settle for just allowing the error to hang over my first script.

I ran irb in the terminal.

I ran the file I had got correct again & the file with the error message:

Error message in terminal. Incorrect Ex25 of learning Ruby the hard way

I tried to work out what was the difference between the two files.

Maybe it was the directories they were saved in?

I check and sure enough they were saved in different directories.

So I saved the error file in the same directory as the file that worked…. STILL the error message!!

I could see no other difference so I ….

Copied and pasted the text from the working file to the error file.

Then something terrible happened!

BOTH the files stopped working!!!!

The same error message appeared for the first file and now the working file was returning ‘false’ when I ‘required’ it with irb:

Ex25 script from learn ruby the hard way returning false in the terminal

Possible cause of this problem:

Too many files with the same or similar name in the same directory?

I deleted all but one… And like magic ..

IT WORKED !!!

I ran the working script for Ex25 in the terminal and followed the instructions on how to use irb to call it’s functions.

Here are my results and my explanation of what is happening:

The correct script for Ex25

Script for exercise 25 learn ruby the hard way. no errors

Running the script in command line ‘irb’

Ex25 in the terminal correct

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

I have labeled the points where I had to think a bit about how it was working. Here is my explanation:

1.   Prints ‘wait’  because the function is acting on the ‘words’ array which is not sorted. The sorted array is called ‘sorted_words’.

2.   ‘Words’ array has had the first and last (“all’ and ‘wait’ ) values shifted off  in the print function.

3.  Calling on the ‘sorted_words’ array, not the ‘words’ array which has the missing values. Therefore ‘all’ is still in the array.

4….Seems to be missing from the picture … So I clearly deemed it irrelevant then therefore i will do the same again now..

5.  Using the original ‘sentence’ variable and passing this through the function. It is breaking this sentence variable into an array every time it encounters a space. Then using Ex25.sort_words function to sort this array of words.

6.  It is taking the original variable ‘sentence’, breaking it into an array of words then printing the first and last value of that array.

 

So we have now come to the end of my struggling with exercise 25 of Learn Ruby the Hard way. I hope you have enjoyed and found useful  my higgledy piggldy problem solving which eventually resulted in me beating the error messages given by running my script.  Please do contact me if you are by a slim chance reading this & need any help understanding it.

Enjoy, 🙂