Is Ruby's `end` delimiter redundant? [closed] - ruby

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
Why do you need to write the end delimiter in Ruby? Can it not be interpreted from the indentation, like in Python or CoffeeScript?
class String
COLORS.each do |color,code|
define_method "in_#{color}" do
"<span style=\"color: ##{code}\">#{self}</span>"
end
end
end
Would look much better to me as
class String
COLORS.each do |color,code|
define_method "in_#{color}" do
"<span style=\"color: ##{code}\">#{self}</span>"
If not, will it be possible in the future or are there any workarounds? Is there any language that compiles into Ruby (like CoffeeScript compiles into JS)?

In Ruby spaces are not significant. So, one needs to clearly mark where block of code starts and ends.
If this looks like a syntactic overhead to you, then you should look at Python :) (I don't like it for exactly this reason: significant spaces)

The reason is just the taste of the language designers (starting from Matz). Many people just don't like indentation-based languages. Given that, it's nevertheless funny that some of those (like HAML or Coffeescript) prove to be rather successful in the greater Ruby world.
Nevertheless, Ruby itself will probably never be indentation based. If you want to use a general purpose language with that feature, you should take a look at either Coffeescript (which compiles to Javascript) or Python.

It's a language design choice. If you like space based block delimiters use Python.

I agree that it's redundant, but currently the only way around it would be to use braces instead (I'm guessing you'll agree that this is even more horrible):
class String
COLORS.each { |color,code|
define_method "in_#{color}" {
"<span style=\"color: ##{code}\">#{self}</span>" } }
end

It could be inferred from the indentation if Ruby paid attention to indentation. Most popular languages today, with Python being a big exception, don't have semantically significant indentation.

Some languages do exactly that (notably Haskell and Python) but the down-side is that it is much more awkward to normalize indentation like this as there's less redundant information. It also means that the use of tabs versus spaces would become a matter of significant holy war, as opposed to just personal preference (and discussion in the bar after work).

Related

Should languages offer a syntactic alternative to method chaining? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
DOM, ThreeJS and now canvas have all had libraries written to provide method chaining (perhaps most familiar from jQuery). Chaining has also been used in core C libraries.
These fluent interfaces avoid unnecessary repetition of the object of interest. Compare:
var cx = cq(640, 480);
cx.drawImage(image, 0, 0);
cx.fillStyle("#ff0000");
cx.fillRect(64, 64, 32, 32);
cx.blur();
cx.appendTo("body");
to:
cq(640, 480)
.drawImage(image, 0, 0)
.fillStyle("#ff0000")
.fillRect(64, 64, 32, 32)
.blur()
.appendTo("body");
It could be argued that the former "traditional" style is over-verbose, and violates DRY.
To avoid repetition of the cx variable, some languages allows us to express a set of calls using a with statement:
with ( cq(640, 480) ) {
drawImage(image, 0, 0);
fillStyle("#ff0000");
fillRect(64, 64, 32, 32);
blur();
appendTo("body");
}
Whilst JavaScript's with statement is dangerous in the presence of typos, Scala's more restrictive with statement is safe to use, and Haxe also offers import of functions to the local scope through its using keyword. Unfortunately Java and C offer no such shortcut, forcing us to choose between traditional code or chaining.
Should language authors consider a safe with-like statement as an alternative to method chaining, or are there good reasons to avoid it? If such a feature is desirable, what form should it take?
One concern I have with method chaining is that the ambiguity about the subject of the later calls in the chain may prevent optimizations previously available when compiling code where repeated use of cx was explicit. For example, if the calls to cx's methods do not overlap, they could be parallelized, but it may be harder for the compiler to be sure of this in the chained example.
Another disadvantage, as rambo points out below, is that methods designed for chaining are unable to return any other value, which seems rather wasteful.
It's called Method Chaining. It frequently appears in the discussion of a Fluent Interface.
Perhaps the biggest drawback is that you cannot return a value, because you must return the implied object to allow chaining. Not all methods make sense without returning a value, and then you end up with an interface that has some chainable methods, and some not.
I don't think it indicates a missing language feature, because there's no serious loss of functionality without it. But language support for somethign like this might be interesting.
It's not a missing language feature, instead it is a language feature. If it was missing then it wouldn't be possible to do it in Javascript.
This is not syntax. Instead, it is a design pattern. And it's called chaining. In fact, there are libraries that implements chaining alone. DED|Chain for example is a library that implementes chaining for YUI2 which was not written with chaining in mind.
A specialized syntax like with (which is indeed implemented in js like you mentioned) is problematic regardless what you call it (you suggested using the name "on" but it will have all the problems that "with" has).
The problem is, inside a code block, it can be confusing to a human (the compiler is not confused) weather the method or variable refers to method of the object or if there was a typo and it accidentally refers to a global variable or a variable that is not part of the object but is in scope.
Of course, you could say that it is the job of the programmer to make sure that they don't use variable and method names that may cause confusion. In which case you can use with.

Why there are some many ways to create Strings in Ruby? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 11 years ago.
I already seen this one Why are there so many slightly different ways to do the same thing in Ruby? but it doesn't help a bit. Having multiple slightly different semantics and syntax for the same thing is IMHO confusing and counterproductive. I was trying to find some spec, or rationale on why this is so, but they're nowhere to be found (unlike Java and Python where every language feature is well documented with motivation etc.).
It's not just String, it's everything. What I'm looking for is a generic explanation on why the japanese think that having 100 ways to do the same thing is better than one explicit way. Remember that we're talking about programming language, that's not a musical instrument, or a paint brush, it's a tool to get the job done and have fun along the way. It's not fun to read some code and wonder why she used %<hello kitty> instead of "hello kitty", especially when you're looking for a bug.
I see the benefit in standardization, which is a related concept. I hope everyone else does. Why doesn't Ruby support some 100 versions of customized HTTP protocol, for the same reason they support 100 ways to create a String?
The reason there's many different ways to create a string is because there's many reasons you might need a string. Since strings are the backbone of many applications, it makes sense that this facility is robust and varied.
Once you're used to it, you'll find the rigid quotation systems in other languages to be more of a nuisance than anything. HTML often requires using both single ' and double " quotes for embedded JavaScript or other attributes, and unless you want to render your string into unreadable pulp by spiking in backslashes \ before any of them you'll be better off with the %q[ ... ] type method of quoting.
Any good toolbox has a variety of tools. Don't complain that your wrench set is confusing because it has so many different sizes of wrench. Sometimes you'll need a specific one, and then you'll be grateful. Many of these methods have been borrowed from languages like Perl, and Perl is inspired by other things like bash.
Typical use cases:
double_quotes = "typical use case with #{variables}"
single_quotes = 'strict string literals'
alternate_double_quotes = %Q[<for html="tags('with both quotes', 'and #{variables}')">]
alternate_single_quotes = %q[<for html="tags('with both quotes')">]
inline_string = <<END
Useful for long blocks of freeform
text such as sample data or templates.
END
I've found that the %q[ ... ] method comes in handy when trying to express multi-line strings that contain quotes as is often the case with SQL:
execute(%q[
INSERT INTO examples (id, feature_code)
SELECT id, CONCAT('example_', feature_code)
FROM things
GROUP BY foo
ORDER BY bar
])
It is relatively easy to spot [ ... ] pairings but not as easy when you have many escaped quotes. It's easy to miss a closing quote unless you have a syntax highlighting editor.

Any method to write Ruby without adding "end"? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 11 years ago.
Ruby is a beatifull language, but with a key word "end" which I hates to write many many times.
Is there any method by which I can write concise code without writing "end" every time?
Ok, this is partially non-responsive, but originally, begin ... end was the paradigm. And by originally, I mean languages you or I have never seen; things called funny names like Algol. Some languages (FORTRAN, Basic) staggered along for years with only single-statement conditionals.
Then C, and later, Java, came along and took over the world. They had { .. }. and that was not bad.
Python and a few others (including a microcode assembler I wrote years before Python was invented) have experimented with using indent for block structure. Nice solution but apparently it wasn't all that popular.
All of those worked but there were various issues.
Believe it or not, Ruby's syntax design no-doubt involved consideration of all these other less-than-perfect dead ends.
My suggestion is: give it another chance just the way it is.
Ruby merges the groundbreaking and technically worshipped Smalltalk and Lisp with the practical and actually useful Perl. For whatever reason, Smalltalk and (((Lisp))) haven't succeeded in 30 and 55 years, roughly, and Perl is fading. Ruby is by far the most advanced language ever to become popular.
The future is Ruby (and Python and JavaScript) and people like Ruby for a reason. One of those reasons is the really user-friendly syntax.
Believe me, the alternatives are worse.
Keep trying!
You don't actually have to write end at all to write Ruby:
Foo = Class.new {
define_method(:bar) {
puts "I don't recommend this"; \
return 42 \
if (:what_is_going_on?)
}
}
Foo.new.bar # => 42
Expect other Rubyists reading your code to wonder what got through your mind, though...
Another possibility without any end that replaces all the dreadful end with your favorite character:
# encoding: utf-8
define_singleton_method(:_){|code|
eval(code.gsub("◊", "e\156d"))
}
_ <<-EOC
class Foo
def bar
if :what_is_going_on?
puts "I don't recommend this either"
return 42
◊
◊
◊
p Foo.new.bar # => 42
EOC
Or replace _ with your own parser that generates ends according to the indentation!

Is it bad style to use return at the beginning of a function to avoid doing unnecessary work? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
Say we have a function foo(), and a bool bar. The work foo does is of no use if bar is false. What is the most proper way to write foo()?
1
foo() {
if(!bar)
return;
doWork();
}
2
foo() {
if(bar)
doWork();
}
Option 1 has the aesthetic advantage that doWork() (ie, the rest of the function) is not indented, but the disadvantage that if you don't look at the early return statement, you may assume that doWork() is called every time you call foo().
In general, is it bad practice to code in style 1, or should it be a personal preference?
Some people will always say to you the "have a single exit point" mantra.
Sometimes, if you need to perform a specific operation on every exit point, it makes a lot of sense. I'd say it's crucial to keep sanity, in this specific case.
Now, if you doesn't have this need, I, personally, see no problem in just exiting as soon as you can and keeping the code on level of ident lower.
I've seen people wrapping the whole code in a do { ... } while (0); block just to keep the single exit point rule, using a break instead of a return. It drives me crazy. But it can be a useful device in some situation.
Overall, use common sense and use what makes more sense in your specific problem.
Style 1 is very useful for guarding statements. Like this:
void work() {
if (!something)
return;
//do the job
}
Otherwise, I would say it depends on the situation. If the if is tightly connected with the following logic, I will use style 2, otherwise I will usestyle 1.
To summarize: always use the one which makes your code more cleaner and readable.
My two cents' worth: If you keep your functions small, multiple returns aren't a real issue. In large functions (which probably should be refactored, but sometimes aren't), multiple return statements--especially from within nested control structures--start to behave like gotos, making the function more difficult to reason about.
The proper way to code a function is to have a single entry point and a single exit point. Doing this makes it easier to maintain and debug an application. Based on your examples, you should write code using the second style that you presented:
foo() {
if(bar)
doWork();
}
This a personal preference, and very subjective - you're likely to see any number of opinions on this. IMHO, there is nothing wrong with either style. Each displays control flow in a reasonable manner, and option 1 can actually be very useful in checking certain function parameters, etc.

Importance of commenting your code [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 14 years ago.
How do you explain your team mates the importance of commenting the code they write? I know some coders who write episodic comments while others leave a lot to be expected, what do you expect when you read comments?
There are some minimums:
All functions and classes should be commented
Try/Catch and exception handling is better to be commented
Constants hard coded in the code should be definitely
dummy objects and dummy classes, as well as TO-DO parts should be commented
When you get a code from a URL, the address should be cited in the comments for further consideration and copyright infringement problems
Also commits to the version control system should be well commented
Although comments should be kept to minimum, there is no need to comment a for loop definition when it is obvious,
I usually set ground rules for my programmers, they stick to it when it is well defined
The best comments are always concise, in a few words. It should say what's not obvious in the code. I see allot of people making obvious and therefore useless comments like:
if x==0 //if x equals 0 then...
oh really?! This is only "polluting" the code, because unless you're learning how to program, its pretty useless.
Even if the code is only yours, you should write comments as if you were about to share it with another programmer that is completely unaware of it. That way you make sure that you will always understand it, and in long term if somebody comes along and picks that code up, that person will be able to understand it and extend/use it.
I see comments as a boost of reusability. And I expect, like every other programmer, to fully understand a block of code with a single, simple and concise comment.
Write comments when you're writing code that's not intuitive. There's really no reason for commenting a method that just iterates an array, but when you fix a bug or have to hack something together to get around an issue, it's good to have a comment so you can quickly understand that code 6 months later (and not accidently undo it).
What do you mean by commenting code?
The actual code, or the function headers?
If you're actually talking about the code, it's a lost cause. You need to get them to write readable code and to break it into meaningful chunks. Commenting bad code doesn't make it into good code, it just leaves an inconsistent mess.
As for header documentation, you have to get them to capture the important things (e.g., surprises, directives) and compromise about trivial things (listing all parameters, repeating what the signature does). People hate documenting functions because most of the effort is spent writing trivial text that almost insults your intelligence (e.g., on getHandleToFile(), "this gets a handle to the file"). Since there are actually a lot less important details than one would expect, they'd be pleasantly surprised and would be more likely to invest the effort in those specific situations.
I think if you are writing code that others may someday have to follow, then it is prudent to leave good comments about what things are doing. If you are just writing something for yourself, the tendency is strong to leave minimal or none at all. That being said, I have had the "not so luxury" of having to go back to code I wrote 8 years ago and didn't comment adequately, in a language I don't use anymore (class ASP) and I can tell you, I wish I had left more comments!
I try to comment most of my public methods and classes, and in those comments you can read what the method does, what the meaning of the parameters is, and, if applicable, what the output will be.
I also sometimes put comments inside my methods, but, there I do not comment what I'm doing, but why I am doing it like that.
if the language you are writing in is not human readable, i suggest very granular method and procedure level comments.
if the language you are writing is human readable (C#, VB, etc..) i suggest that you use somewhat detailed comments at the method level and minimal comments at the procedure level.
Include comments for document generation on methods and classes.
Don't comment every line.
If you are doing something expected or that is not obvious from the code, explain why in comments.
The most important thing to do in commenting is to tell the truth. The number of times I've been investigating a bug only to find a section of code that is "less than obvious" along with a comment that says it's supposed to do the opposite to what it is doing. Who wins? You decide...
On a related note, any comment that is longer than the section it is documenting is normally too long.

Resources