Is the if statement considered a method?
No, this is not considered a method, as you have already seen in other answers. However, if you had a question: “Does it behave like a method?”, Then the answer may be yes depending on the language. Any language that supports first-class functions can do without a built-in constructor / statement such as if . Ignore all the fluffy things like return values ​​and syntax, because basically it is just a function that evaluates to a boolean and , if true , then it executes some block of code. Also ignore OO and functional differences, because the following examples can be implemented as a method of the Boolean class in any language that is used as Smalltalk.
Ruby supports blocks of executable code that can be stored in a variable and passed to methods. So, here is the custom _if_ function implemented in Ruby. The material in { .. } is part of the executable code passed to the function. It is also known as a block in Ruby.
def _if_ (condition) condition && yield end
We can do the same in C, C ++, Objective-C, JavaScript, Python, LISP and many other languages. Here is a javascript example.
function _if_(condition, code) { condition && code(); } _if_(42 > 0, function() { console.log("Yes!"); });
Anurag Jan 19 '12 at 5:22 2012-01-19 05:22
source share