What Does the |Variable| Syntax Mean

What does @@variable mean in Ruby?

A variable prefixed with @ is an instance variable, while one prefixed with @@ is a class variable. Check out the following example; its output is in the comments at the end of the puts lines:

class Test
@@shared = 1

def value
@@shared
end

def value=(value)
@@shared = value
end
end

class AnotherTest < Test; end

t = Test.new
puts "t.value is #{t.value}" # 1
t.value = 2
puts "t.value is #{t.value}" # 2

x = Test.new
puts "x.value is #{x.value}" # 2

a = AnotherTest.new
puts "a.value is #{a.value}" # 2
a.value = 3
puts "a.value is #{a.value}" # 3
puts "t.value is #{t.value}" # 3
puts "x.value is #{x.value}" # 3

You can see that @@shared is shared between the classes; setting the value in an instance of one changes the value for all other instances of that class and even child classes, where a variable named @shared, with one @, would not be.

[Update]

As Phrogz mentions in the comments, it's a common idiom in Ruby to track class-level data with an instance variable on the class itself. This can be a tricky subject to wrap your mind around, and there is plenty of additional reading on the subject, but think about it as modifying the Class class, but only the instance of the Class class you're working with. An example:

class Polygon
class << self
attr_accessor :sides
end
end

class Triangle < Polygon
@sides = 3
end

class Rectangle < Polygon
@sides = 4
end

class Square < Rectangle
end

class Hexagon < Polygon
@sides = 6
end

puts "Triangle.sides: #{Triangle.sides.inspect}" # 3
puts "Rectangle.sides: #{Rectangle.sides.inspect}" # 4
puts "Square.sides: #{Square.sides.inspect}" # nil
puts "Hexagon.sides: #{Hexagon.sides.inspect}" # 6

I included the Square example (which outputs nil) to demonstrate that this may not behave 100% as you expect; the article I linked above has plenty of additional information on the subject.

Also keep in mind that, as with most data, you should be extremely careful with class variables in a multithreaded environment, as per dmarkow's comment.

what is the definition of variable

This question is tagged C, but the C standard does not define “variable.” In the sense asked about, the 2018 standard uses the word mostly in non-normative notes, examples, and footnotes. The few places where it is used in normative text are in supplementary language features added later (such as threads and atomic objects), and I do not regard their uses there as firm information about the meaning.

In the standard, what are commonly thought of variables are indeed described via “objects” (regions of storage) and “identifiers” (names). In this regard, your answer is correct.

However, we do not know the context of your class. It may have included discussion of the term “variable,” and that discussion may have defined it as your teacher required for the test.

Historically, variables represented things whose values could be changed, and they were named because of that. The evolution of programming languages to have constant objects came later, giving rise to some conflict between the historic name and the current use. I expect this is part of why the C standard moved away from “variable” and toward “object” and “identifier.” Insisting on use of the term only in its historic meaning is unduly rigid unless it was an explicit definition presented in the course.

What does - mean in Python function definitions?

It's a function annotation.

In more detail, Python 2.x has docstrings, which allow you to attach a metadata string to various types of object. This is amazingly handy, so Python 3 extends the feature by allowing you to attach metadata to functions describing their parameters and return values.

There's no preconceived use case, but the PEP suggests several. One very handy one is to allow you to annotate parameters with their expected types; it would then be easy to write a decorator that verifies the annotations or coerces the arguments to the right type. Another is to allow parameter-specific documentation instead of encoding it into the docstring.

What is the meaning of '*' and '&'?

This is possibly one of the most confusing things in Go. There are basically 3 cases you need to understand:

The & Operator

& goes in front of a variable when you want to get that variable's memory address.

The * Operator

* goes in front of a variable that holds a memory address and resolves it (it is therefore the counterpart to the & operator). It goes and gets the thing that the pointer was pointing at, e.g. *myString.

myString := "Hi"
fmt.Println(*&myString) // prints "Hi"

or more usefully, something like

myStructPointer = &myStruct
// ...
(*myStructPointer).someAttribute = "New Value"

* in front of a Type

When * is put in front of a type, e.g. *string, it becomes part of the type declaration, so you can say "this variable holds a pointer to a string". For example:

var str_pointer *string

So the confusing thing is that the * really gets used for 2 separate (albeit related) things. The star can be an operator or part of a type.

What does this symbol mean in JavaScript?

See the documentation on MDN about expressions and operators and statements.

Basic keywords and general expressions

this keyword:

  • How does the "this" keyword work, and when should it be used?

var x = function() vs. function x()  —  Function declaration syntax

  • var functionName = function() {} vs function functionName() {}

(function(){})()  —  IIFE (Immediately Invoked Function Expression)

  • What is the purpose?, How is it called?
  • Why does (function(){…})(); work but function(){…}(); doesn't?
  • (function(){…})(); vs (function(){…}());
  • shorter alternatives:
    • !function(){…}(); - What does the exclamation mark do before the function?
    • +function(){…}(); - JavaScript plus sign in front of function expression
    • !function(){ }() vs (function(){ })(), ! vs leading semicolon
  • (function(window, undefined){…}(window));

someFunction()()  —  Functions which return other functions

  • Two sets of parentheses after function call

=>  —  Equal sign, greater than: arrow function expression syntax

  • What's the meaning of "=>" (an arrow formed from equals & greater than) in JavaScript?

|>  —  Pipe, greater than: Pipeline operator

  • What does the "|>" operator do in JavaScript?

function*, yield, yield*  —  Star after function or yield: generator functions

  • What is "function*" in JavaScript?
  • What's the yield keyword in JavaScript?
  • Delegated yield (yield star, yield *) in generator functions

[], [ value ], Array()  —  Square brackets: array notation

  • What’s the difference between "Array()" and "[]" while declaring a JavaScript array?
  • What is array literal notation in javascript and when should you use it?

If the square brackets appear on the left side of an assignment ([a] = ...), or inside a function's parameters, it's a destructuring assignment.

{}, { key: value }, { [key]: value }  —  Curly brackets: object literal syntax (not to be confused with blocks)

  • What do curly braces in JavaScript mean?
  • Javascript object literal: what exactly is {a, b, c}?
  • What do square brackets around a property name in an object literal mean?
  • How does this object method definition work without the "function" keyword? (ES2015 Method definitions)

If the curly brackets appear on the left side of an assignment ({ a } = ...) or inside a function's parameters, it's a destructuring assignment.

`${}`  —  Backticks, dollar sign with curly brackets: template literals

  • What does this `…${…}…` code from the node docs mean?
  • Usage of the backtick character (`) in JavaScript?
  • What is the purpose of template literals (backticks) following a function in ES6?

//  —  Slashes: regular expression literals

  • Meaning of javascript text between two slashes

$  —  Dollar sign in regex replace patterns: $$, $&, $`, $', $n

  • JavaScript replace() method dollar signs

()  —  Parentheses: grouping operator

  • MDN: Grouping operator


Property-related expressions

obj.prop, obj[prop], obj["prop"]  —  Square brackets or dot: property accessors

  • JavaScript property access: dot notation vs. brackets?

?., ?.[], ?.()  —  Question mark, dot: optional chaining operator

  • Question mark after parameter
  • Null-safe property access (and conditional assignment) in ES6/2015
  • Optional Chaining in JavaScript
  • Is there a null-coalescing (Elvis) operator or safe navigation operator in javascript?
  • Is there a "null coalescing" operator in JavaScript?

::  —  Double colon: bind operator

  • JavaScript double colon (bind operator)

new operator

  • What is the 'new' keyword in JavaScript?
  • What is "new.target"?

...iter  —  Three dots: spread syntax; rest parameters

  • (...rest) => {}  —  What is the meaning of “…args” (three dots) in a function definition?
  • fn(...args)  —  What is the meaning of “foo(…arg)” (three dots in a function call)?
  • [...iter]  —  javascript es6 array feature […data, 0] “spread operator”
  • {...props}  —  Javascript Property with three dots (…), What does the '…rest' stand for in this object destructuring?


Increment and decrement

++, --  —  Double plus or minus: pre- / post-increment / -decrement operators

  • ++someVariable vs someVariable++ in Javascript


Unary and binary (arithmetic, logical, bitwise) operators

delete operator

  • What is the purpose of the delete operator in Javascript?

void operator

  • What does `void 0` mean?

+, -  —  Plus and minus: addition or concatenation, and subtraction operators; unary sign operators

  • What does = +_ mean in JavaScript, Single plus operator in javascript
  • What's the significant use of unary plus and minus operators?
  • Why is [1,2] + [3,4] = "1,23,4" in JavaScript?
  • Why does JavaScript handle the plus and minus operators between strings and numbers differently?

|, &, ^, ~  —  Single pipe, ampersand, circumflex, tilde: bitwise OR, AND, XOR, & NOT operators

  • What do these JavaScript bitwise operators do?
  • How to: The ~ operator?
  • Is there a & logical operator in Javascript
  • What does the "|" (single pipe) do in JavaScript?
  • What does the operator |= do in JavaScript?
  • What does the ^ (caret) symbol do in JavaScript?
  • Using bitwise OR 0 to floor a number, How does x|0 floor the number in JavaScript?
  • Why does ~1 equal -2?
  • What does ~~ ("double tilde") do in Javascript?
  • How does !!~ (not not tilde/bang bang tilde) alter the result of a 'contains/included' Array method call? (also here and here)

%  —  Percent sign: remainder operator

  • What does % do in JavaScript?

&&, ||, !  —  Double ampersand, double pipe, exclamation point: logical operators

  • Logical operators in JavaScript — how do you use them?
  • Logical operator || in javascript, 0 stands for Boolean false?
  • What does "var FOO = FOO || {}" (assign a variable or an empty object to that variable) mean in Javascript?, JavaScript OR (||) variable assignment explanation, What does the construct x = x || y mean?
  • Javascript AND operator within assignment
  • What is "x && foo()"? (also here and here)
  • What is the !! (not not) operator in JavaScript?
  • What is an exclamation point in JavaScript?

??  —  Double question mark: nullish-coalescing operator

  • How is the nullish coalescing operator (??) different from the logical OR operator (||) in ECMAScript?
  • Is there a null-coalescing (Elvis) operator or safe navigation operator in javascript?
  • Is there a "null coalescing" operator in JavaScript?

**  —  Double star: power operator (exponentiation)

  • x ** 2 is equivalent to Math.pow(x, 2)
  • Is the double asterisk ** a valid JavaScript operator?
  • MDN documentation


Equality operators

==, ===  —  Equal signs: equality operators

  • Which equals operator (== vs ===) should be used in JavaScript comparisons?
  • How does JS type coercion work?
  • In Javascript, <int-value> == "<int-value>" evaluates to true. Why is it so?
  • [] == ![] evaluates to true
  • Why does "undefined equals false" return false?
  • Why does !new Boolean(false) equals false in JavaScript?
  • Javascript 0 == '0'. Explain this example
  • Why false == "false" is false?

!=, !==  —  Exclamation point and equal signs: inequality operators

  • != vs. !==
  • What is the difference between != and !== operators in JavaScript?


Bit shift operators

<<, >>, >>>  —  Two or three angle brackets: bit shift operators

  • What do these JavaScript bitwise operators do?
  • Double more-than symbol in JavaScript
  • What is the JavaScript >>> operator and how do you use it?


Conditional operator

?:…  —  Question mark and colon: conditional (ternary) operator

  • Question mark and colon in JavaScript
  • Operator precedence with JavaScript's ternary operator
  • How do you use the ? : (conditional) operator in JavaScript?


Assignment operators

=  —  Equal sign: assignment operator

  • What is the difference between the `=` and `==` operators and what is `===`? (Single, double, and triple equals)

This symbol is also used for default parameters or default values in a destructuring assignment:

  • what does (state = {}) => state means
  • What does ({"key": "value"} = {}) syntax mean inside a JavaScript function

%=  —  Percent equals: remainder assignment

  • Having Confusion with Modulo operator

+=  —  Plus equals: addition assignment operator

  • How does += (plus equal) work?

&&=, ||=, ??=  —  Double ampersand, pipe, or question mark, followed by equal sign: logical assignments

  • What purpose do &&=, ||= and ??= serve?
  • Replace a value if null or undefined in JavaScript
  • Set a variable if undefined
  • Ruby’s ||= (or equals) in JavaScript?
  • Original proposal
  • Specification

<<=, >>=, >>>=, &=, ^=, |= — Double less than, double greater than, triple greater than, ampersand, caret, or pipe followed by equal sign: bitwise assignments

  • What do these JavaScript bitwise operators do?

Destructuring

  • of function parameters: Where can I get info on the object parameter syntax for JavaScript functions?
  • of arrays: Multiple assignment in JavaScript? What does `[ a, b, c ] = [ 1, 2, 3 ]` mean?
  • of objects/imports: Javascript object bracket notation ({ Navigation } =) on left side of assign


Comma operator

,  —  Comma operator (not to be confused with the comma used in variable declarations)

  • What does the comma operator do in JavaScript?
  • Comma operator returns first value instead of second in argument list?
  • When is the comma operator useful?


Control flow

{}  — Curly brackets: blocks (not to be confused with object literal syntax)

  • JavaScript curly braces with no function or json

Declarations

var, let, const  —  Declaring variables

  • What is the difference between "let" and "var"?
  • Are there constants in JavaScript?
  • What is the temporal dead zone?
  • var a, b;  —  Comma used in variable declarations (not to be confused with the comma operator): JavaScript variable definition: Commas vs. Semicolons


Label

label:  —  Colon: labels

  • What does the JavaScript syntax foo: mean?
  • What does ':' (colon) do in JavaScript?


Other

123n  —  n after integer: BigInt

  • What does character 'n' after numeric literal mean in JavaScript?

#  —  Hash (number sign): Private methods or private fields

  • What does the # symbol do in JavaScript?

_  —  Underscore: separator in numeric literals

  • Javascript numeric separators?
  • Is there a Javascript equivalent to the Ruby syntax using underscores (e.g. 10_000 = 10000) to make larger integers human readable?

What does this syntax mean? (Duration) - String?

(Duration) -> String? is the type of the variable t. In particular here, it's a function type.

It means "function that takes a Duration as argument and returns a nullable String".

The other piece of code shows that the variable t is indeed being used as a function afterwards:

val str = t(Duration.seconds(3))

// which could also be written as
val str = t.invoke(Duration.seconds(3))

What does the TYPE in java mean?

Without evidence, I believe you're talking about Java's Generics support...

Generics allow you to abstract over types

Before Java 5 it was difficult to provide classes that were capable of supporting multiple different types of Objects without having to code for each specific situation, so it was common for people to pass Object instead.

This leads to many difficult choices to make at runtime, you'd have to do a runtime check to see if it was possible to cast a given Object to a usable type...for example

List myIntList = new LinkedList(); // 1
myIntList.add(new Integer(0)); // 2
Integer x = (Integer) myIntList.iterator().next(); // 3

Now, this is reasonably obvious, but if you were passed just a List, you'd have to check each and every element in the list for correctness...

But now, we can do this...

List<Integer> myIntList = new LinkedList<Integer>(); // 1'
myIntList.add(new Integer(0)); // 2'
Integer x = myIntList.iterator().next(); // 3'

This is a contract that basically says "This list only contains Integer type's of objects".

With generics you can construct a single class that is capable of handling multiple different data types or a family of data types (ie constraint the parameter so that it must be extended from a particular parent type).

Iterator<? extends Number> itNum;

Basically says, this will contain objects that inherit from Number, include Integer, Long, Double, Float...

Often in method and class decelerations you will see something similar to...

public class MyGenericClass<T> {...}

or

public class MyGenericClass<T extends MyBaseObject> {...}

This allows you to refer to T as if it were a concrete object type, for example...

public class MyGenericClass<T extends MyBaseObject> {
private T value;
public MyGenericClass(T value) {
this.value = value;
}
}

This allows the compiler (and JVM) to essentially "replace" the marker T with a concert type (okay, it's a little more complicated then that, but that's the magic)...

This allows to do things like...

... new MyGenericClass<MySuperObject>(new MySuperObject());
... new MyGenericClass<MySuperSuperObject>(new MySuperSuperObject());

And know that it will only ever accept the type of object I specify...

Have a read through the link in the first paragraph, I'm sure it can do more justice then I can ;)

What does & sign mean in front of a variable?

It means pass the variable by reference, rather than passing the value of the variable. This means any changes to that parameter in the preparse_tags function remain when the program flow returns to the calling code.

function passByReference(&$test) {
$test = "Changed!";
}

function passByValue($test) {
$test = "a change here will not affect the original variable";
}

$test = 'Unchanged';
echo $test . PHP_EOL;

passByValue($test);
echo $test . PHP_EOL;

passByReference($test);
echo $test . PHP_EOL;

Output:

Unchanged

Unchanged

Changed!



Related Topics



Leave a reply



Submit