Ruby Terminology Question: Is this a Ruby declaration, definition and assignment, all at the same time?

StackOverflow https://stackoverflow.com/questions/672135

Question

If I say:

x = "abc"

this seems like a declaration, definition and assignment, all at the same time, regardless of whether I have said anything about x in the program before.

Is this correct?

I'm not sure what the correct terminology is in Ruby for declarations, definitions and assigments or if there is even a distinction between these things because of the dynamic typing in Ruby.

@tg: Regarding your point # 2: even if x existed before the x = "abc" statement, couldn't you call the x = "abc" statement a definition/re-definition?

Was it helpful?

Solution

  1. Declaration: No.
    It doesn't make sense to talk about declaring variables in Ruby, because there's nothing analogous to a declaration in the languages. Languages designed for compilers have declarations because the compiler needs to know in advance how big datatypes are and how to access different parts of them. e.g., if I say in C:

    int *i;
    

    then the compiler knows that somewhere there is some memory set aside for i, and it's as big as it needs to be to hold a pointer to an int. Eventually the linker will hook all the references to i together, but at least the compiler knows it's out there somewhere.

  2. Definition: Probably.
    A definition typically set an initial value for something (at least in the familiar compiled languages). If x didn't exist before the x = "abc" statement, then I guess you could call this a definition, since that is when Ruby has to assign a value to the symbol x.

    Again, though, definition is a specific term that people typically use to distinguish the initial, static assignment of a value to some variable from that variable's declaration. In Ruby, you don't have that kind of statement. You typically just say a variable is defined if it's been assigned a value somewhere in your current scope, and you say it's undefined if it hasn't.

    You usually don't talk about it having a definition, because in Ruby that just amounts to assignment. There's no special context that would justify you saying definition like there is in other languages.

    Which brings us to...

  3. Assignment: Yes.
    You can definitely call this an assignment, since it is assigning a value to the symbol x. I don't think anyone will disagree with that.

OTHER TIPS

Pretty much. And if, on the very next line, you do:

x = 1

Then you've just re-defined it, as well as assigned it (its now an integer, not a string). Duck typing is very different to what you're probably used to.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top