Any method to write Ruby without adding "end"? [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 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!

Related

Is indentation obligatory in Ruby? [duplicate]

This question already has answers here:
Do I need to indent my code in Ruby?
(3 answers)
Closed 7 years ago.
I got some errors in Ruby on Rails' code, but I don't know if that's because it's not indented. Does Ruby code work without indentation?
With a project that's strictly Ruby, your indentation will not matter. Here's a SO answer to the same question that has a good example of functioning Ruby code with poor indentation. If you're curious about proper indentation style in general, Github's Ruby style guide will be a good reference for you.
Since you mentioned Rails specifically, I imagine you might be running into errors with your template code. If you're using a template like slim or jade (your views will have .slim or .jade or .haml), indentation can be important, and the lack of indentation can cause errors. For example,
h1 Example code
- #foos.each do |foo|
p = foo
Is valid slim code, but
h1 Example code
- #foos.each do |foo|
p = foo
will generate a syntax error.
As #sawa says, indentation is not obligatory but it is good practice as it allows your code to be much easier to read (for humans), which means it's far easier to catch any errors. According to the book Eloquent Ruby a sensible practice is to use two spaces per line for indentation since this is clearly an indent, but without using up too much room on the line. The book also advises not to use tabs since there is no universal length of a tab, so they can vary in length greatly. To see all this in action...
Code without indentation:
class Human
def laugh
puts "laugh"
end
def cry
puts "cry"
end
The code isn't quite right, but it's not immediately obvious where the error is.
Code with indentation and sensible spacing:
class Human
def laugh
puts "laugh"
end
def cry
puts "cry"
end
Here it's much easier to see that the end that should be aligned with the class opening is missing. In short, yes indent your code and also use sensible spacing (such as the space between the methods). It'll help you and any humans working with or reading your code.
Indentation isn't as strict as it is in python. Your code should work fine if indentation is off, but may not be maintainable or readable to another developer.

Is Ruby's `end` delimiter redundant? [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.
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).

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.

Ruby gotchas when it comes to class inheritance [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'm coming from a static typed language background (C#/Java), and while I have developed apps using Rails, I'm still not fully confident when in comes to class design.
Are there any 'gotchas' when it comes to inheritance in Ruby?
Maybe things to do with static variables, constructors (initializers), the meta/singleton class (I think the official name is something like eugene class)?
I have read a ruby book and I'm looking for those with real world experience to point out things that might not be so obvious in practise.
The biggest gotcha I encountered is that "class variables" (variables whose names start with ##) don't behave the way you would expect. The variable is actually shared among the class and all the subclasses, so you can't change its value in the subclasses without affecting the parent class. Here's an example:
class Foo
##x = 1
def self.x
##x
end
end
class Goo < Foo
##x = 2
end
puts Foo.x # => 2
puts Goo.x # => 2
Instead of using class variables, you might want to use instance variables of the class object, but then you don't automatically get inheritance so you have to define all those variables each time you define a new subclass:
class Moo
#y = 1
def self.y
#y
end
end
class Noo < Moo
#y = 2
end
puts Moo.y # => 1
puts Noo.y # => 2
Alternatively, just make a class method (e.g. self.x) that returns the desired value. Then you get inheritance and the ability to override it in subclasses.
One thing I've discovered as I'm using Ruby more and more is to avoid using inheritance unless it really is necessary and logical to do so. So much more can be accomplished in Ruby by using modules and including them in your class than in C#/Java.
Doing so will make your design more flexible and easier to use in any unforeseen scenarios where a consumer of the design doesn't want to "use up" their parent class just to satisfy your library/API. Additionally, this helps me follow the "favor composition over inheritance" wisdom in a new way I couldn't in C#/Java.
Not sure if this qualifies as a 'gotchya' or simply something new to consider compared to those other languages.

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.

Resources