Manufacturing Authority And Trust

TrustI’ve said this before and I’ll say it again, software development is about more than just processes and technology, there are always people involved. And whenever there are people involved, it makes everything a whole lot more complicated. No matter what position you’re in, manager, team lead, just a regular developer you will at one point need to negotiate, compromise, convince someone that you’re right, convince someone that they are wrong, convince someone that someone else is wrong, the possibilities are endless when you’re dealing with people. And I don’t just mean outsiders, the business, the stakeholders etc., you can often find more than enough of these kinds of situations within your very own team. So how do you make sure that your voice is heard, that your words are given the weight that they surely deserve (they do deserve it right?), how do you get your teammates, managers, customers to listen to you and give your opinions due consideration? There is no one sure-fire way, but it all hinges around two very important attributes:

  • authority
  • trust

Trust is when people listen to you and give weight to your opinion because they have a personal relationship with you. This relationship could be friendship, love or simply knowing that you won’t steer them wrong based on empirical evidence (i.e. you’ve come through for them in the past). Authority is when people perceive you to have some expertise, knowledge or power that they don’t have. You may be celebrated for your knowledge, or have the weight of experience on your side or simply have been placed in charge, regardless people will tend to defer to authority sometimes without even realizing they are doing so. So, in order to make sure you’re heard and listened to you need to get yourself either some authority, some trust or preferably some of both and there are three ways of doing this.

Have It

Authority and trust are funny in that they feed off each other. If people consider you authoritative then they will automatically tend to trust you more, it also works the other way, the more people trust you the more weight they will give to your opinion (i.e. you’ll be more of an authority in their eyes). So, the best and most foolproof way of getting authority and trust is to already be an authority. That may seem obvious, but don’t dismiss it, experts have it easy, so it may be in your best interest to try and get to that point.

Getting to the point where you’re considered an expert is hard work. You need to put yourself out there, be involved in the community, share your opinions, write, talk and get your face known by others. But once you do get there, no matter what situation you find yourself in, whatever you say will carry significant weight. You might be the newest person on a team with no domain or system knowledge, but people will still tend to give your views a lot of consideration. Picture this, you’re discussing some code design and Uncle Bob (Robert C. Martin) comes in and decides to weigh in with a few gems of his own, or perhaps you might be chatting about refactoring and Martin Fowler walks by and shares his thoughts, you will probably treat their views with a lot more consideration than you would if Joe Schmoe, developer from down-the-hall, said the same thing.

The best way to make sure you’re a heavy-weight in any discussion/negotiation is to actually be widely considered to be an authority on the subject. It doesn’t even have to be your main area of expertise a related field will do, true authority casts a long shadow.

Fake It

But what if you’re not yet considered an expert (you may be working your way up there but you’re not there yet)? You’ll still sometimes be the new guy on a team or find yourself negotiating scope (or whatever) with your customers. In this situation your best bet would be to rely on trust, as I said above, if people trust you they will automatically consider you more of an authority. However gaining trust is tough because it is a very time-consuming process. Building a relationship that results in genuine trust does not happen overnight, you need to work on it and give it time to mature. Once you do have it though you’re almost in as a good a position as if you were a genuine authority, people will listen to you because of the relationship you have built up with them. But, this does not help you if you’re the new guy or simply have not yet had time to build the necessary level of trust.

In this case you can try to fake some authority. I don’t mean you should lie and try to pass yourself off as an expert in an area you know nothing about, but the old adage does apply – fake it till you make it. If you’re already working on becoming an authority in an area you will have a level of expertise, you may not have universal recognition as yet, but it is possible to make people believe that you’re more of an authority than you actually are. You can point out some previous work you have done in the field, or highlight the recognition you have received before, the idea here is to simply make people aware of the fact that you know what you’re on about and that some other people know it too. Until your fame runs before you :), you will actually need to let people know that you have some knowledge in the area under discussion. If you do this right, people will give your words more weight, however if you do this wrong, people will tend to dismiss you as boastful and self-promoting. You therefore need to be very confident in your interpersonal skills before you go down the route of trying to artificially inflate your authority. So, if you’re not comfortable with it, don’t do it, there is another way.

Borrow It

Borrow

Have you ever been to a conference or a talk where the material was to be presented by two people, one famous (i.e. someone you’ve heard of) and one not so much. You were probably attracted to the talk by the name of the more famous person, in your eyes they had authority so you wanted to hear what they had to say. But, when you actually went to the presentation, the material was almost fully presented by the less famous of the two people with the more famous taking a background role. Chances are you still enjoyed the presentation (people who have built up authority don’t tend to put their name on inferior material), but you might have been somewhat puzzled by why the famous person’s name was even on the material at all. You may have shrugged it off or had a chuckle about how the ‘celebrity’ was riding their fame and reputation (without doing much work). But, that was not at all the case. In reality the less famous of the two presenters was borrowing some authority from the more famous.

Chances are the two people presenting were probably friends or colleagues. The less famous of the two had something interesting to share, but knew that he was unlikely to attract many people (perhaps the material didn’t seem interesting until you dig into it), so he asked his more famous friend to share some of his authority to help attract more of an audience. In effect people came to see the celebrity but stayed due to the quality of the material. You can do the same thing in your day-to-day work and you don’t even have to be friends with any famous people. There are probably people you work with who have built up a lot of trust with others (e.g. they may have been working there a while and have a lot of great relationships). If you also have a good relationship with that person and need to convince some other people of something, it may be a good idea to borrow some authority/trust from your friend to help you. Perhaps you can ask them to be involved on your side or simply get them to introduce you, to get your presentation started on the right note.

If you’re new to a workplace, but were referred by a friend, it is a good idea to get your friend to introduce you around. That one gesture will help other people associate you with someone they already trust/like, some of this will be transferred to you which means you will start to form great relationships with your teammates much faster (think of it as a kind of shortcut) and start building some trust of your own.

The lessons here are as follows. If you want your opinions to always have genuine weight in any discussion related to your field, then you need to work on building your authority in that field. Until others begin to recognize that you really know what you’re talking about you will need to make sure they are aware of the fact that you’re working on being an authority and then you need to talk real sense to back up your claim. But, if you can’t convince others by yourself then try and borrow some authority from an influencer or someone who has built up a lot of trust. If you can’t do any of those it does not mean your voice will not be heard, but it does mean yours will be just one of many. Throughout all this make sure that you always try to build genuine relationships with the people you work with, your teammates, your managers, your customers and users. The trust you gain will help you be perceived as more of an authority which in turn will mean your opinions will be solicited and given extra weight every time.

Images by notsogoodphotography and carrinated

Using Ruby Blocks And Rolling Your Own Iterators

BlocksI recently covered Ruby block basics in my post, More Advanced Ruby Method Arguments – Hashes And Block Basics. I mentioned that blocks are not really method arguments and also covered the two different types of block syntax. Towards the end of that post I promised to examine Ruby blocks more deeply and I am going to try and do that here.

In my opinion there are several interesting things about blocks:

  • is there any other difference between the two different types of block syntax besides the fact that one is predominantly used for single line blocks and the other for multi-line?
  • in what context are blocks normally used and how does it look from the perspective of the methods that take blocks as ‘parameters’?
  • is passing parameters to blocks similar to passing parameters to a method (i.e. is the syntax just as rich, can you have default values etc.) and what scope do those parameters have?
  • can a block be a first class parameter and can you pass it around easily as opposed to just using it as a quasi-parameter like we normally do?

Examining each one of those in turn can give one a reasonably solid understanding of blocks, so that’s what we’re gonna do.

The Two Different Block Notations

As we know there are two different types of block syntax, the curly brace syntax e.g.:

ruby [1,2,3,4,5].each {|i| print "#{i} "}

and the do..end syntax e.g.:

ruby [1,2,3,4,5].each do |i| print "#{i} " end

Aside from looking different and being used for single or multi-line blocks, there is one major difference between the two types of syntax – precedence. As we know all expressions in Ruby return a value, this is no different when we execute an iterator. So if we want to use a value that is returned by an iterator that takes a block (e.g. print it out) we can normally do so. When we use curly brace notation this is not a problem e.g.:

ruby print [1,2,3,4,5].each {|i| i}

this will print out:

12345

as we would expect. But if we try to do the same with the do..end syntax e.g.:

ruby print [1,2,3,4,5].each do |i| i end

we get the following error:

`each': no block given (LocalJumpError)

this is due to the fact that the method call to print has higher precedence over the do..end block syntax so that what we actually have happening is the following:

ruby print([1,2,3,4,5].each) do |i| i end

to get this to work correctly we need to wrap the whole thing in braces e.g.:

ruby print([1,2,3,4,5].each do |i| i end)

It is not a major difference but something to be aware of.

Learn About Blocks By Implementing Our Own Iterator

The best way I have found to learn how blocks and iterators work together is to implement some of your own starting with a really simple case. Lets implement an infinite loop iterator of our own:

ruby def infinite_loop while true yield end end

We can call it in the following way, notice that we pass a simple block:

ruby infinite_loop {puts 'Looping Infinitely'}

this will print out ‘Looping Infinitely’ forever since the loop inside out iterator method has no exit condition and just keeps yielding to the block. So far so easy, so lets move on to something more complex. Let’s say we need to add another iterator to the array class that can work with the array elements in reverse (I am aware that Array has a method to reverse itself). We could do this by opening up the Array class and putting our new iterator in:

ruby class Array def reverse_iterate current_index = self.size-1 while current_index >= 0 yield self[current_index] current_index -= 1 end end end

We now have an exit condition for the loop in our iterator which means we won’t yield to the block more times than there are values in the array. We can then call our new iterator method in the following fashion:

ruby [2,4,6,8].reverse_iterate { |i| print "#{i} "}

This is all pretty simple, a couple of things to note, the call to yield inside out new method, this is what causes the method to accept a block in the first place. The second thing is the parameter we pass to the yield method. By passing one parameter to yield we cause the block that the iterator takes to also take one parameter. If we passed two values to yield then our block would need to take two parameters as well. So, the above prints out the array because we yield each of the array values to the block (in reverse order) and just output it:

8 6 4 2

But what if we want our new method to not only take a block but also have some sort of default behavior when no block is provided? This is fairly simple to do, we just need to use the Kernel.block_given? method:

ruby class Array def reverse_iterate if block_given? current_index = self.size-1 while current_index >= 0 yield self[current_index] current_index -= 1 end else print self.reverse end end end

we can now call our iterator with no block at all:

ruby [2,4,6,8].reverse_iterate

Our default behavior just prints out all the array values in reverse, concatenated together:

8642

The last thing to note is the fact that yield can actually return a value from the block back to the iterator. The value yield returns is the result of the last expression executed in the block. We can take advantage of this to, for example, collect the values that the block returns on every iteration and return a new array with all the new values as the result of the iterator method call, e.g.:

ruby class Array def reverse_iterate if block_given? new_array=[] current_index = self.size-1 while current_index >= 0 new_array << yield(self[current_index]) current_index -= 1 end else print self.reverse end new_array end end

If we then call out iterator method with a block that squares all the values it receives:

ruby puts [2,4,6,8].reverse_iterate { |i| i*i}

the result returned from the method call will be an array with the values of our original array but reversed and squared. We can print this out:

64
36
16
4

This can be pretty handy and is incidentally similar to how the more complex Ruby iterator methods (such as map) work.

Block Parameters

Using block parameters is very similar to using method parameters, the rules are pretty much identical. If you’re using Ruby 1.9 you’ve got all the features like default arguments and optional arguments which you can mix and match pretty much any way you like. If you’re on Ruby 1.8, you can still have optional and default arguments but you’re a little more limited in how you can mix and match them. So to give an example, you could create an iterator that yields 4 parameters to the block in the following way:

ruby class Array def reverse_iterate current_index = self.size-1 while current_index >= 0 yield self[current_index], 'Value', current_index, 'Index' current_index -= 1 end end end

You can then call this iterator with a block but rather than using 4 parameters, you can use two with the second being a catch-all (remember the * notation):

ruby [2,4,6,8].reverse_iterate do |value, *others| puts "#{others[0]} = #{value}, #{others[2]} = #{others[1]}" end

You use the values from the catch-all parameter just like you would an array, so our iterator call would output:

Value = 8, Index = 3
Value = 6, Index = 2
Value = 4, Index = 1
Value = 2, Index = 0

Fairly straight forward. What is more interesting is the scope that variables have once we are inside the block. In the simplest case we may call an iterator with a block from another method, which may already have some variables defined:

ruby def some_crazy_method random_variable=5 [1,2,3].each do |i| puts "Array value=#{i}, Random variable=#{random_variable}" end end

It is curious that in this case we actually have access to these variables from within the block. Calling the above method prints out the following:

Array value=1, Random variable=5
Array value=2, Random variable=5
Array value=3, Random variable=5

As you can see we are able to print out _randomvariable from within the block and it is set to the same value as it was outside the block. But, what happens when we have a variable outside the block and use a variable with the same name as a block parameter e.g.:

```ruby def some_crazy_method i=5 puts “Before block i=#{i}”

[1,2,3].each do |i| puts “In block i=#{i}” end

puts “After block i=#{i}” end```

The behavior here depends on whether you’re using Ruby 1.8 or 1.9. With Ruby 1.8 it is still the same variable as the one defined outside the scope of the block, so if we assign a new value to that variable within the block this value will be available outside of the block. So calling the above method in Ruby 1.8 would produce:

Before block i=5
In block i=1
In block i=2
In block i=3
After block i=3

Notice that i now retains the last value it had within the block. In Ruby 1.9 however, the variable within the block is not the same as the one outside of the block so the output in 1.9 would be:

Before block i=5
In block i=1
In block i=2
In block i=3
After block i=5

As you can see the variable retains it’s old value after the block completes. Ruby 1.9 also provides another feature to do with variable scope. If you want to pass a variable to the block that is not automatically assigned to, but you don’t want to accidentally pass in a variable which has already been initialized (prior to the block and is therefore in scope within the block) you can do the following:

```ruby def some_crazy_method some_variable=5

puts “Before block some_variable=#{some_variable}”

[1,2,3].each do |i;some_variable| puts “In block i=#{i}” some_variable = i end

puts “After block some_variable=#{some_variable}” end```

By passing a variable to the block after the semicolon, we essentially say that we want to have a variable with that name local to the block and unrelated to a variable with the same name outside the block e.g.:

Before block some_variable=5
In block i=1
In block i=2
In block i=3
After block some_variable=5

This seems to be of limited utility and is not available in Ruby 1.8 (it will produce a compilation error).

Block As Closures

That’s right, you can use a block as a closure and pass it around and call it whenever you like. It is a reasonably advanced feature, but essentially you can do the following:

```ruby def method_with_block_as_closure(&block) another_method block end

def another_method(variable) x=25 variable.call x end

method_with_block_as_closure {|i| print “I am happy block #{i}”}```

By prepending the method parameter with the & symbol you tell the method to treat the block it gets as a closure and assign it to that parameter. We can then pass this parameter around to other methods just like we would any other. When we actually want to call the block we simply need to use the call method on the variable that currently contains the block, passing in any parameters that the block expects. In our case the result of the above code would be to execute the print method that was called inside the block e.g.:

I am happy block 25

This is a very basic, surface view of how to use blocks as first class parameters (closures). At this stage, this is really all we need to know, but I do plan to dig more deeply into how and why this works in a later post (i.e. Procs etc.). If you’re interested in that, then make sure you grab my feed so you don’t miss it. That’s all I wanted to cover regarding blocks, hope you found it interesting.

Image by Holger Zscheyge

A Wealth Of Ruby Loops And Iterators

LoopI remember when I first started looking at Ruby, I’d be browsing some code and see yet another way of looping/iterating over stuff. Whenever that would happen I would think, “…Ruby sure has a lot of different ways to iterate over things”, but I also remember wishing that someone would just put all the different ways to loop and iterate over stuff together so that you don’t have to discover them in a piecemeal fashion. Most resources I’ve seen tend to gloss over this a little bit by introducing the while loop and the each iterator and quickly moving on to more interesting things, expecting you to discover the rest on your own (nothing wrong with that by the way).

As you may have guessed from my recent posts on Ruby method arguments (and more advanced method arguments), the Ruby case statement and others, I am kind-of discovering Ruby in my own way and looking more closely at things that I find of interest. So I’ve decided to fulfill my own wish and put together all the different ways to loop over stuff in Ruby.

Ways To Loop Over Stuff In Ruby

I classify looping and iterating in Ruby into two distinct buckets:

  • simple ways to loop/iterate – this is where we loop over elements and work with each element as we iterate over it, but we basically don’t need to retain any knowledge of what we did to a particular element once we move on to the next unless we explicitly decide to store some info (this is how the basic loops and iterators operate)
  • complex ways to loop/iterate – this is where in addition to iterating over elements we transform the elements we are iterating over in some way and retain this information when we complete the loop (this is how more complex iterator-style methods such as map, collect etc. work)

I will only be covering simple ways here, there are more than enough of those, and I will look at more complex ways at a later point. Anyways lets dive in.

Unconditional Looping With Loop

The simplest looping construct in Ruby is the loop method. Technically speaking it is not a looping construct but is infact an iterator method since it takes a block, but because it is the simplest of all it comes first. The simplest version of it is the infinite loop:

ruby loop {puts "HELLO"}

This will just infinitely print out HELLO, not particularly useful, but if you ever need a simple way to create an infinite loop, there you go :).

Of course Ruby provides us with all the loop termination and control keywords that allow us to make the loop method more useful than it has been so far. I am talking about the break, next and redo keywords. The break keywords allows us to exit a loop at any point e.g.:

ruby i=0 loop do i+=1 print "#{i} " break if i==10 end

This will print out the numbers from 1 to 10 all on the same line:

1 2 3 4 5 6 7 8 9 10

Since we are using the break keyword, the loop will exit when the value of i hits 10.

You can use the next keyword to skip over the current iteration of the loop and go on to the next one:

ruby i=0 loop do i+=1 next if i==3 print "#{i} " break if i==10 end

This will print out the numbers from 1 to 10 all on the same line, but will skip number 3 because we skipped that iteration of the loop:

1 2 4 5 6 7 8 9 10

You can also pass a value to both next and break, but it is only useful in the case of break as it will become the value that the loop returns (remember, every expression in Ruby returns a value), so we could do something like this:

ruby i=0 puts(loop do i+=1 print "#{i} " break 'Hello' if i==10 end)

This will print out the numbers from 1 to 10 followed by ‘Hello’ since that is the value that the loop expression will return:

1 2 3 4 5 6 7 8 9 10 Hello

I also mentioned the redo keyword, but it makes little sense to use it with the loop method, so I will save it for later.

The While Loop

The while loop in Ruby is just like the standard while loop in any other language nothing too fancy:

ruby i=1 while i < 11 print "#{i} " i+=1 end

This will print out the numbers from 1 to 10 as you would expect:

1 2 4 5 6 7 8 9 10

The Until Loop

The until loop is similar to the while loop but the logic is reversed:

ruby i=1 until i > 10 print "#{i} " i+=1 end

Once again we print out the number 1 to 10 as expected, as you can see the loop condition for the until loop is the opposite of the while loop:

1 2 4 5 6 7 8 9 10

I did mention I was gonna cover the redo keyword, well now is as good a time as any. The redo keyword allows you to restart the loop from the beginning without evaluating the condition again. It is not very useful in the examples we’ve been doing so far where our terminating condition is affected by what we do within the loop (e.g. incrementing the value), all we can do is create a more fancy infinite loop that will keep printing out ever incrementing numbers:

ruby i=1 until i > 10 print "#{i} " i+=1 redo if i > 10 end

This will keep incrementing the value of i and will keep printing it out:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 ...

The reason this happens is because redo restarts the loop from scratch but does not evaluate the terminating condition, so even though i is greater than 10 we still do another iteration and increment the value and then hit the redo again and go for another ride (yee-haw :)).

Using While And Until As Modifiers And Simulating Do..While

Ruby also allows you to use the while and until keywords as modifiers, which means you can put them at the end of an expression just like you can do with the if statement. You can therefore create much shorter versions of the loops above:

ruby i=0 print "#{i+=1} " while i < 10

ruby i=0 print "#{i+=1} " until i == 10

Both will print out the numbers from 1 to 10 all on the same line as has become the custom for us :).

This property of the while and until keyword also allows us to simulate the do..while loop in Ruby. Ruby has no looping construct that is guaranteed to always execute at least once (like the do..while), but we can do the following:

ruby i=11 begin print "#{i} " i+=1 end while i < 10

This will print out the number 11, even though we’ve set the loop to terminate when the value of i is less than 10, the loop is guaranteed to execute at least once, so we get the value of i printed out once.

We can do something similar with until:

ruby i=10 begin print "#{i} " i+=1 end until i == 11

This will print out 10 and then exit the loop as the exit condition will be reached.

The For Loop

If we discount the loop method then the for loop acts as a kind of bridge between looping constructs and iterators in Ruby. The for loop is still a looping construct but it acts almost like an iterator without actually taking a block. You can use the for loop to loop over values in a range e.g.:

ruby for i in 1..10 print "#{i} " end

or values in an array e.g.:

ruby for value in [1,2,3,4,5,6,7,8,9,10] print "#{value} " end

Both of these will once again print out the numbers from 1 to 10.

The Each Iterator

Now we come to iterators. Iterators are methods that take blocks and execute that block as many times as there are iterations. There are simple iterator methods and more complex ones (we are only looking at the simple ones), the simplest iterator method is – each. All iterables (such as arrays and hashes) in Ruby will have an each method that will allow you to loop over the values in the iterable and do something with each one. For example you can iterate over the values of an array using each and pass in a block that will print out each one e.g.:

ruby [1,2,3,4,5,6,7,8,9,10].each {|value| print "#{value} "}

You know what this will print out :). If you want to do something more complex you can use the do..end block syntax and have all sorts of fun with each of the values you’re iterating over. Simple, moving on.

The Times Iterators

The times iterator is similar to you classic for loop in other languages and will allow you to execute a loop and perform an action (according to the block you write) x number of times e.g.:

ruby 10.times {|i| print "#{i} "}

This will print out the numbers 0 to 9, so we’re really bucking a trend here.

0 1 2 3 4 5 6 7 8 9

Because we are using the times iterator we are only interested in how many times we iterate rather than what each value will be so 0 to 9 is ok. Times is a really useful shortcut when you have a number and need to iterate that many times. If you do need to control what values the block will get on each iteration as well as how many times you iterate you can use the upto and step iterators.

The Upto And Step Iterators

Once again it is similar to your classic for loop in that we execute from number x up to number y (y needs to be bigger than x obviously). So if we want to get back to printing 1 to10 we can do the following:

ruby 1.upto(10) {|i| print "#{i} "}

This prints out what we expect:

1 2 3 4 5 6 7 8 9 10

We can also iterate while skipping over a range of numbers on every iteration e.g.:

ruby 1.step(10, 2) { |i| print "#{i} "}

This skips 2 rather than skipping 1, which is equivalent to doing i+=2 if you were using your classic for loop (or a while loop), so we end up printing out the following:

1 3 5 7 9

We are in the home stretch now only one more to go.

The Each_Index Iterator

Sometimes we have an array and we don’t want to loop over every value but rather want to loop over every index, this is where the _eachindex iterator comes in handy:

ruby array = [10,20,30,40,50,60,70,80,90,100] array.each_index {|i| print "#{array[i]} "}

The block gets the index of the array on every iteration and we can then use that to print out the value (not useful but illustrates the point):

10 20 30 40 50 60 70 80 90 100

As expected we printed out all the values in the array, it is 1 to 10 but 10 times bigger for extra awesomeness :).

There is one last thing to mention about simple loops and iterators, the retry keyword. I mentioned the redo keyword, way up above towards the start, which can restart a while or until loop without re-evaluating the condition. Well, the retry keyword is similar but it can be used for iterators and for loops. The retry keyword will also force an iterator or for loop to restart but it will re-evaluate the arguments passed to the iterator. Note that the redo keyword can also be used for iterators and the for loop but the retry keyword can not be used within while and until loops and similar.

That’s all the simple ways to loop/iterate over stuff in Ruby. If you think I’ve missed some or simply have something to add feel free to let me know in the comments. In the meantime enjoy getting loopy (and iteraty ) :).

Image by PanCa SatRio