Skip to content
Advertisements

Taglanguage

Understanding Ruby Symbols

Ruby is an interpreted language. It is dynamically typed and uses a new memory for a variable. A variable has a name and a value. Symbols are an optimized variable that holds single instance of memory. It is good for variables that assume the same values across the program such as hash table keys.

h = {'my_key' => 123}

The storage for my_key is allocated each time my_key is used. That’s waste of memory and many related bookkeeping tasks by the Ruby interpreter.

So declaring the key as a symbol makes sense as only one copy of my_key is kept in memory.

h = {:my_key => 123}

You have to use the : operator with each usage of a symbol.

irb(main):003:0> new_hash={:my_key => 123}
=> {:my_key=>123}

irb(main):004:0> new_hash[:my_key]
=> 123

# You must use the :

irb(main):005:0> new_hash[my_key]
NameError: undefined local variable or method `my_key' for main:Object
    from (irb):5
    
irb(main):006:0> new_hash['my_key']
=> nil

Written with StackEdit.

Golang: Switch-case does not fall through!

Unlike C/C++ switch-case statements, Golang switch case does not fall through.

package main
import (
	"fmt"
)

func main() {
	fmt.Print("Go runs on ")
	os := "darwin"
	switch os {
	case "darwin":
	case "linux":
		fmt.Println("Linux.")
	default:
		// freebsd, openbsd,
		// plan9, windows...
		fmt.Printf("%s.\n", os)
	}
}

The above code does not print anything!

package main
import (
	"fmt"
)

func main() {
	fmt.Print("Go runs on ")
	os := "darwin"
	switch os {
	case "darwin":
	fallthrough
	case "linux":
		fmt.Println("Linux.")
	default:
		// freebsd, openbsd,
		// plan9, windows...
		fmt.Printf("%s.\n", os)
	}
}

You have to add fallthrough statement to make it work. The above code prints Linux.

Forward declaration of a structure in C

What do you think of following code?

/*
 * decl.h
 */
struct junk {
    int a;
};

----------------------------------------------
/*
 * fwd.c
 * We have not included the header file decl.h.
 */
#include 
struct junk;

int main()
{
    struct junk *ptr;
    printf("%d", ptr->a);
}

You will get compilation error that structure object ptr is incomplete. This is misleading if you do not go through all included header files. cscope will make you believe that definition exists. You just wonder till you find out that structure was never defined in fwd.c!

%d bloggers like this: