Collections: Working with Hashes in Ruby

Collections: Working with Hashes in Ruby

Hashes are data structures that contain key => value pairs and are denoted by curly braces {}

hash = {:key => value}  # old syntax
hash = {key: value} #new syntax

They can have multiple key value pairs.

hash = {:key1 => value1, :key2 => value2, :key3 => value3}

To add onto a hash:

hash[:key4] = value4
hash[:key5] = value5
hash   
# => {:key1 => value1, :key2 => value2, 
      :key3 => value3, :key4 => value4, :key5 => value5}

To delete a key and its value:

hash.delete(:key1)
hash = {:key2 => value2, :key3 => value3, :key4 => value4, :key5 => value5}

To retrieve a value of a specific key:

hash[:key5] 
# => value5

hash.merge(other_hash) merges hash with other_hash and creates another hash.

hash.merge!(other_hash) is a mutating version that modifies the calling hash object.

Iterate with .each method

hash.each { |key, value| puts #{key} #{value} }

 

Advertisement
Collections: Working with Arrays in Ruby

Collections: Working with Arrays in Ruby

DISCLAIMER: I’m a noob to programming. This is not a guide or something that you should use to learn how to be a programmer. Some of it might be incorrect. This is just for me, John Gamboa, to record my progress in learning Ruby. Now that’s out of the way, on the to the article.

This is an array for a refresh:

array = [1, 2, 3, 3, 4, 5, 5]

Looking for something?

array.first   # returns the first element
              # => 1
array.last    # returns the last element
              # => 5
array[4]      # returns the element in that index (index starts at 0)
              # => 4

Looking for a change? These methods will change the array.

array.pop       # removes last element and mutates
array.push      # add element to the end and it mutates
array << object # "shovel" is the same as push and it mutates

More changes coming.

array.map       # iterates over each element, applies block, returns new array
array.delete_at # deletes value at an index and mutates
array.delete    # deletes all instances of a value and mutates
array.uniq      # returns a new array of all unique values, doesn't mutate
array.uniq!     # mutates array, only unique values are left.

Let me re-iterate with “each” and “select”:

The “each” method iterates through each element of an array (we are still talking arrays here) and applies a block of code to each element.

The “select” method is similar in that it loops through each element but it returns a new array and that new array includes elements that return true to the expression provided. If the return is nil or falsey, then nothing is entered into the array for that element.

select – returns a new array based on the block’s return value. If the return value evaluates to “true” (or checks if it’s truthy) then the element is selected.

Common array methods

array.include?(value) checks if value is in the array.

array.flatten takes an array with nested arrays and turns it into a one-dimensional array.

array.flatten! is flatten that mutates

array.each_index iterates through the index and passes the index of each element into the block.

array.each_with_index iterates through the array passes two parameters into the block, value and index.

array.sort returns a sorted array.

array.product(array2) combines two arrays like this:

[1, 2, 3].product([6, 7]) # => [[1, 6], [1, 7], [2, 6], [2, 7], [3, 6], [3, 7]]

each vs map: use each for iteration and it returns the original array, use map for transformation returns a new array

map – returns a new array based on the block’s return value. Each element is transformed based on the return value.

Changing Objects Passed Into Methods – Ruby

Changing Objects Passed Into Methods – Ruby

When a variable is passed into a method, it may or may not be changed based on the operation that takes place inside the method.

For example:

def no_mutation(str)
  str + ", John?
end

words = "How are you"
no_mutation(words)

puts words    # => "How are you"

Notice how the “+” operator doesn’t change or mutate the “words” variable? That’s because “+” is not destructive. It concatenates “How are you” and “, John?” but that complete string isn’t assigned to anything nor the original object “How are you” changed by the “+” operator. If the line were changed to str = str + “, John?”, the str variable would then point to a new string object “How are you, John?” but it would not change the original string object that was passed into the method.

Now let’s look at the following code.

def mutation(str)
  str << ", John?
end

words = "How are you"
mutation(words)

puts words    # => "How are you, John?"

This time string object that “words” points to is changed by the method. That’s because the << in the method is destructive and mutates the object that is referenced by the variable.

Conclusion:

Depending on the operation going on in the method, the object passed in may or may not be changed. It’s a good reason to use irb to test your code and see what is happening to the objects in your methods.

Local Variable Scoping Rules in Ruby- Part Two

Local Variable Scoping Rules in Ruby- Part Two

Continuing on the topic of local variable scoping rules, we come to the scoping rules for methods.

Check this code:

a = 5

def some_method
  a = 3
end

puts a # => 5 (Why 5 and not 3?

When the code executes “puts a”, it displays 5 and not 3. The reason is our 2nd rule.

Rule #2 – Methods create their own scope outside of execution flow.

We’ll visit methods a little more later in the blog.

Blocks and Nests

Rule #3 – A block creates a new scope for local variables, nested blocks created nested scopes, and the scope of a variable is determined by where it is initiated.

Let’s take a look at the following code for illustration.

2.times do
  a = 'hello' # a is initialized inside the 2.times block.
  puts a
end

loop do
  puts a     # => uh oh NameError
  break
end

puts a      # => man! another NameError

The variable “a” is initialized in the first block and therefore can’t be accessed the second block or the last “puts a” line. That also means that peer blocks cannot access variables initialized in other blocks. Which also then means we could reuse “a” for another variable in the second block. We really shouldn’t use letters for variable names since they should be a lot more descriptive.

Nested blocks create nested scopes. If you initiate a variable outside of any blocks it will be accessible by blocks and inner blocks. If a variable is initiated in a block it is accessible by blocks created inside the block it was created in. Confused? I guess this concept is better served with actual code.

a = 1            # first level variable accessible by blocks and nested blocks

loop do
  b = 2          # second level variable

  loop do
    c = 3        # third level not accessible to first or second level
    puts a       # => 1
    puts b       # => 2
    puts c       # => 3
    break
  end
  
  puts a         # => 1
  puts b         # => 2
  puts c         # => NameError because c is on 3rd level
  break
end

puts a          # => 1
puts b          # => NameError because b is on 2nd level
puts c          # => NameError because c is on 3rd level

Variable Shadowing

Basically if you have an outer variable and an inner variable with the same name, you prevent the outer variable from being modified by the code where the inner variable exists.

n = 10
[1, 2, 3].each do |n|
  puts n    # will use the block 'n' and ignore the outer scoped 'n'
end
n = 10
1.times do |n|
  n = 11
end
puts n    # => 10 because the outer scope 'n' isn't changed

Rule #4 – The simplest way to avoid variable shadowing is to use descriptive variable names.

Variables and Methods

In contrast to blocks that leak from outer to inner blocks, methods are self contained.

a = 'hello'

def some_method
  puts a
end

# invoke the method
some_method     # => NameError because puts can't access 'a'
  
  def some_method(a)
    puts a
  end

  some_method(5)   # => 5

Rule #5 – Variables can’t leak into a method from outside the method, they have to be passed in explicitly.

Blocks Within Methods

Rule #6 – The rules of block scope remain in full effect inside of a method.

Constants

  USERNAME = 'Boss'

  def welcome
   puts "Welcome, #{USERNAME}!"  end

  welcome     # => Welcome, Boss!

Rule #7 – Constants are accessible by methods and can be initiated in an inner scope.

Local Variable Scoping Rules in Ruby – Part One

DISCLAIMER: At the time of this post, I, John Gamboa, was not a Ruby or programming expert. A total noob and I wrote this more to familiarize myself with the rules than anything else. What flows through sticks to you.

A scope of a local variable determines if it is accessible or not. For instance, if you were to code this:

var1 = 1
loop do
  puts var1
  var1 = var1 + 1
  break
end
puts var1

Run the code and you’ll find that the last line “puts var1” results in 2 being displayed. Why? Because the variable var1 in the first line is accessible and there can be modified by the loop block.

Rule #1 – Outer scope variables are accessible by the inner scope.

But what about block of code? What does the last line produce?

array = [6, 5, 4]
for i in array do
  var1 = 5
end
puts var1

It produces 5. Even though var1 was initiated inside the do/end block, var1 is accessible outside it. For a variable to be inaccessible in a do/end block, the do/end block needs to immediately follow a method invocation. “for” in the code above is not a method invocation, in contrast to the following code:

loop do
  var1 = 1
  puts var1
  var1 = var1 + 1
  break
end
puts var1

Since “loop” is a method invocation, the do/end loop following it creates a new block which prevents var1 from being accessed by “puts” in the last line. It results in an error with “undefined local variable or method…” in it. That’s because var1 was initialized inside the loop block, or in the inner scope, and the “puts var1” is outside the block and can’t access var1.

Which means…

Inner scope variables are NOT accessible outside of the block

First Web Dev Journal Entry

First Web Dev Journal Entry

So for the last few weeks I’ve been learning a web programming language called Ruby at launchschool.com. I decided to delve into web programming because it is a growing industry with lots of demand for skilled developers. With the advent of iPhone and the whole smartphone, mobile, slash always-connected phenomena, demand for web developers and software engineers has skyrocketed and with my background in IT, I figured I’d give it a go and maybe in a couple years be able to add software programming and web development to my repertoire of computer related skills.

Many years ago, I took a class in Visual Basic 6 at a local community college and did fairly well but it was super basic. I had no need for my job at the time nor was I looking to get into programming but I thought it would be good to learn. Not having to use the knowledge I learned back then, needless to say, I knew almost nothing coming into learning and had zero background when I decided to seriously study web development.

After a few weeks, I’m enjoying the process of learning again. I am always challenged by subject matter, because it’s all new to me and it feels like my brain is getting a workout daily. At times my mind feels like mush and other times it feels empowered from having learned AND understood new concepts.

The course encourages starting a blog and so I started this blog as a part of my IT Experiences site. It’s related, right? So, why not? I’ll occasionally post some updates. Not sure what they’ll be about – technical, experiential, both, who knows? Keep checking back to see how I’m doing.

My current plan is to finish the course that in 2 years I can say I have the skills to write a full-stack software program. Full-stack means front-end and back-end programming. Think front end as your smartphone and back-end as the servers in the cloud. What does it mean for me if I can complete this course successfully in 2 years? God only knows.Code

Finding fast forwarders for your DNS server to speed up internet speeds – John Gamboa

Why do you want the fastest DNS servers listed as DNS forwarders on your domain name server? Mainly, to get your internet experience to speed up. Having slow DNS forwarders can affect how long a browser takes to find and load a web page or to start downloading a file. In bad cases I’ve seen some sites become inaccessible because of bad DNS forwarders. Major sites like Google.com and Yahoo.com were getting “Page cannot be found” errors for an entire office!

There’s a quick way to figure which forwarders to set on your server. First, use a DNS benchmark utility. I’ve been using DNSBench and it’s served me well. It’s a free utility that test numerous DNS servers from your location so you can find and use the fastest ones for your computer and network. Even within a city like San Francisco, different locations will get the best results with different forwarders even inside the same building.

DNSBench-Screenshot-John-Gamboa

Download it from here. It’s self contained so you don’t have to install it, just put it in its own directory somewhere on your computer or external drive and run it. Click on Run Benchmark and wait. It’s best not use the PC as much as you can so it can test the DNS servers better and give you a more accurate result.

Once you get the fastest two or three identified, you can put those as your forwarders on your DNS server. Here is a screenshot of one of my DNS servers forwarders page. I set the priority based on the speed results I got from my DNSBench results. You can get by with 2 or 3 but as you can see from my screenshot, you can put more. You’ll notice that even DNS servers provided by the same companies can have differing speeds. After setting this up for one of my clients and changing the forward queries time out to 1 second – which you have to be careful of because slow internet plus short timeouts can result in the forward query loop because you’re not giving enough time for the request to go out and come back – internet surfing drastically improved.

Hope this helps.

DNS Forwarders John Gamboa

Temporary Profiles for New ADUC Users on Different Computers

Here’s a weird one that I just ran into recently on a network we inherited from another IT consulting firm.

A little background on this issue. The environment has a Windows active directory with Windows 7 clients. Several GPOs configured including folder redirection. A new user was just set up and a day later started getting a temporary profile.

Our tech team tried some things that have worked before to fix temporary profiles. We tried creating a new profile but no local profile directory got created. Tried deleting the backup profile registry key but that wasn’t there, system restore didn’t fix it either. We tried putting the user in their own OU with a folder redirection GPO. But no matter what we tried, they would continue to get a temporary profile. Copying the user resulted in the same problem. The problem followed the new user even when logging into another computer.

If an existing user logged into the computer they logged in just fine. That led us to look at Active Directory. What ended up getting this problem resolved was to inherit inheritable permissions on the user that had this problem. There must have been something in the new user’s AD permissions that wasn’t right and we were thinking the GPO requires some inheritable permissions for it correctly set up the profile on the computer. After that was done the new user received a normal user profile.

ADinherit

Weird!

The New Microsoft

A New Microsoft

If you’ve been keeping up with tech news, no doubt you’ve heard about the upcoming release of Microsoft’s latest operating system called Windows 10. I’m pretty excited about this OS because it has a ton of potential to give Microsoft a much needed boost after its Windows 8/8.1 failed to impress and the seeming failure of Windows Phone 8 which hasn’t really cemented itself as a clear alternative to iPhones and Android smartphones with only 3 percent market share. I am really pulling for Microsoft and Windows 10, and under its new CEO Satya Nadella, it has quickly remade itself in terms of direction, innovation, and speed.

New Direction 

CEO Satya Nadella took the helm last year from former CEO Steve Ballmer. From my point of view this Microsoft under Mr. Nadella has quickly changed from its big company, slow moving, corporate stalwart to a nimble, adaptive, creative, almost startup-like entity that seems to clearly know what it’s future will be like – focusing on mobility and cloud first.

Windows 10

Take a look at how Microsoft has taken new approaches to technology. Let’s examine Windows 10. What’s different with this OS from previous ones? Months before its release, Microsoft has given tens of thousands the opportunity to test the OS before it’s ready for prime time. Windows 8 on the other hand was kept under wraps for a long time before it was released and when it finally hit the market, people in general weren’t to receptive to it, or left utterly confused. It was like a Dr. Jekyll and Mr. Hyde situation. How do I use this stupid computer?!

With Windows 10, ordinary people can download and test the Windows 10 OS and provide feedback. It seems also that Microsoft is listening to its testers and reacting quickly by making changes with each new release that seem to correct some wrongs brought up by users of the beta version of the OS. When Windows 10 hits the market, it’ll be (hopefully) received more warmly than its predecessor.

What about the one OS for all devices approach? Think about it for a moment. From computers, hybrids, tablets, and smartphones to IOT (Internet of Things), to its 84 inch Surface Hub, Windows 10 is designed to run on all those devices. That’s one core OS to run on all things. Coupled with FREE upgrades for current Windows 7/8.1 and Windows Phone 8.1 devices. In addition to this, Microsoft isn’t charging any licensing fees to OEMs for devices 9 inches and smaller. What has happened is OEMs around the world who want to be to Microsoft what Samsung is to Android have started making Windows 10 tablets and smartphones.

Windows 10 for all devices John Gamboa

Windows 10 for all devices
John Gamboa

Even companies that have Android devices now are porting over Windows 10 to existing hardware designs. Check out Xiaomi’s Mi4 running Windows 10. I’m sure other OEMs that currently make Android devices can do the same very easily. This sort of began with Windows 8.1 in a way with HTC’s One M8 for Windows. It’s the exact same hardware as it’s One M8 Android counterpart but running Windows 8.1. And it’s actually a really nice device. Since Samsung pretty much owns Android on tablets and smartphones, I would imagine a new compelling offering in Windows 10 on millions of tablets and smartphones for $0 is making OEMs see opportunity to gain market share on a new platform.

Developers! Developers! Apps! Apps!

This opens the door wide open for developers to reach millions and millions of devices quickly and relatively inexpensively. Why? Because with Windows 10, they need to only develop one app, theoretically, and only make tweaks to the UI/UX based on the form factor of the device it’s running on which Windows “knows” about even with convertible hybrid laptops. Supposedly Windows 10 knows how it’s being used on a hybrid like the Microsoft Surface or a Lenovo Yoga – with a keyboard and trackpad/mouse or as a touchscreen tablet-like device. So as a developer, you can take your base code and apply settings to tailor the UI/UX to the device it may potentially run on.

The tweaks for an app to operate optimally depending on what device is used are supposedly easy to make. I’m not a developer but it sounds like a developer has a grand opportunity to reach millions of devices very quickly once Windows 10 is released. Write one app, publish it to run on computers, tablets, and phones or whatever combination of devices you wish. They don’t have to code 3 different apps, just one plus some UI/UX configuration. And startup or struggling developers have an opportunity to launch in a relatively uncrowded marketplace – Windows Store – and get in on the ground floor of something that may explode. The Windows Store’s lower number of apps compared to Apple’s App Store or Google Play may work out to its benefit allowing new innovative apps to flourish where they might have sat idle or die out in a crowded iTunes App Store or Google Play store.

Ally vs Alienate

In the pre-Nadella days of Microsoft, the company was closed in that it was like our way or the highway in respects to it’s software. What I mean by that, for example, is if you wanted to run Microsoft Office, you had to run it on a Windows device. But with its new mobile-cloud first strategy, Microsoft released Office for iOS and Android and for FREE! Gone are the days, it appears, of the old Microsoft that forced people to use their OS to get the benefits of running the number one office productivity suite in the world. Even Samsung and Microsoft have agreed that Samsung will be loading Microsoft Apps on their Android devices. Something that would have seemed like a far fetched idea not too long ago is becoming more characteristic of this new Microsoft – make allies and don’t alienate. This puts mobility front and center and ties into their new vision. Why not get huge market share in the productivity apps business by providing the mobile version of Office for FREE on iOS and Android tablets and smartphones. Boom! Just like that, the potential to get millions to experience Microsoft productivity on their beloved Galaxy and iPhone/iPad devices.

Office for Android John Gamboa

Office for Android
John Gamboa

Cloud First

With Office apps being top downloaded apps in both iTunes and Google Play, what’s next? Cloud-first! Office 365 is Microsoft’s answer to Google Apps. By many accounts it is a better solution. I won’t go into it here but something as simple as syncing email to Microsoft Outlook which used to be great with Google Apps has become full of problems. Sure Office 365 has not always been the better of the two but Microsoft has a way to reinvent and adapt and still be relevant and Office 365 is now a solid product. Its current offering is a cohesive suite that just works for businesses. And guess what? Outlook paired to Office 365 Exchange just works.

So with millions of Office users on their iPads and Galaxy Smartphones and tablets using Microsoft Office that just works with Office 365, the potential millions of Windows 10 upgrades on existing Windows 7/8 and Windows Phone 8.1 devices, you can see how the mobility and cloud first is beginning to take shape. Microsoft is also churning out really good apps for mobile devices. It’s newly released Outlook app is a 4 start app in both iTunes and Google Play stores and has a really good UI/UX and this was a result of it’s recent purchase of Accompli. This just shows the aggressiveness and how serious Microsoft is taking mobility first. Not wasting time developing a great email client but putting money where their mouth is and buying a company that already had a great app. More to follow with its recent purchases of Sunrise that makes a great calendar app, LiveLoop, a developer of collaboration software. As its products continue to receive good ratings and as people begin to get more exposure to Microsoft, it stands to reason that some percentage will begin to use Microsoft’s cloud services such as Office 365. AND some of those will be willing to pay for the ability to use great apps that work with a great cloud service.

Office for iOS John Gamboa

Office for iOS
John Gamboa

The old mentality of use our stuff from our stuff is no longer viable in today’s environment and Microsoft seems to have embraced that. People love their iPhones and Galaxy devices. They may not want to switch to Windows 10 for phone or to a Surface, but that’s no longer the drive behind the innovation and new open feel of this new Microsoft. It’s mobility and cloud first. OS? Maybe second? Maybe.

But they might want to move over to Microsoft Windows 10, won’t they? If the Microsoft apps are good and the Microsoft cloud offering is good and the experience is good on iOS and Android, maybe the experience on the Microsoft Windows 10 OS is good. Wouldn’t it make sense that some non-Windows users of Office and Office 365 may find it compelling to switch to Windows 10 if they feel the experience would be good as well?

If Windows 10 is well received by the market, if it’s adopted by the millions of Windows 7 consumers and business users, then, if developers start making top notch apps for Windows 10 as a result, then it may become one of the best OS’s to be released by any software company. And this will further Microsoft’s mobility and cloud first vision. And if it doesn’t, it is no longer a stumbling block on the road to the future for Microsoft – MOBILITY AND CLOUD FIRST.

I’m long on Microsoft and so is Wells Fargo who just recently rated MSFT stock as “OUTPERFORM”. I’m excited about this new era of computing and the future of Microsoft.

Why does my computer default to wireless when I’m wired in?

I’ve always wonder why Windows 7 computers configured with a wireless connection would always seem to have slower connections to the network and internet. I found my answer while helping a client with their wireless speeds. They have 100Mbps and which is pretty darn fast. Desktops would always get 80 to 95 Mbps but laptops would get 5 to 10.

What’s happening is that all their laptops are configured to connect to the wireless network and even when docked Windows would put the wireless connection ahead of the wired connection. This caused their wireless network to get so bogged down it would almost become useless.

Solution:

Hidden in the Network and Sharing Center is a setting that allows you to prioritize the network connections. Mac’s make it easier in the Network system preferences screen. You can move the connection up or down on the main screen. Microsoft has buried this setting.

Here’s how you do it. Open up the Network and Sharing Center. Click on “Change adapter settings” on the upper left of the window that pops open.

To get to the secret location, press the Alt key and you’ll see a hidden menu bar. Tip: Alt in most windows brings up the hidden menu for that window.

Click on Advanced then on Advanced Settings.

Find your Local Area Network or Ethernet under Connections. Highlight it and move it to the top using the green arrow on the right. Click OK.

You’re done.

Advanced Network

Network Adapter Advanced Settings

So if you have laptops that use wireless and wired connections, do yourself a favor and give the wired connection the highest priority.

Hope this helps!