Coding the RM way

For as much as it's claimed that RGSS isn't necessarily Ruby, it would be wise to consult the standard styleguide for Ruby anyways: https://github.com/bbatsov/ruby-style-guide

A lot of the issues I see revolve around odd usage of semicolons, explicit returns, and honestly just concepts coming from other languages.

One of the big things that drives me up a wall are people that do something like this:

# Bad - Hanging Indentationsome_method.with.a_longer.chain🙂parameter_1,                                😛arameter_2,                                😛arameter_3,                                😛arameter_4) # Good - Drop to a new linesome_method.with.a_longer.chain(  😛arameter_1,  😛arameter_2,  😛arameter_3,  😛arameter_4)
but that comes down to stylistic quibbles more than anything.

The big thing I would avoid would be using the english operators for and and or. They have extremely low precedence and can make for some annoying issues later. The styleguide above mentions it. Personally I'll only use them for control flow type reasons, such as:

my_method or raise 'Nope' my_method and my_other_method or special_it_failed_method
Granted you can use if/else branches for that, but it makes for a nice amount of succinctness in certain cases.
That's pretty much how I use the 'not' operator. Only in simple statements, when I'm mostly concerned with readability. Everywhere else, '!'.
That's pretty much how I use the 'not' operator. Only in simple statements, when I'm mostly concerned with readability. Everywhere else, '!'.
Just remember that unless is an option as well. That brings up another interesting one:

# Badif !condition  actionend # Better - unless is a natural if notunless condition  actionend # Best - short statements can inline this as a postfix checkaction unless condition # Bad - nil is naturally falsy, don't bother to check for itif checked_object.nil?  checked_object = 'foo'end # Better - Nil is naturally falsy, use it to your advantage, but this is still wrong in this contextunless checked_object  checked_object = 'foo'end # Best - or equals will set a falsy object to the value. This can be incredibly handy for caching valueschecked_object ||= 'foo' # Speaking of caching values, a few method cache options for fun:class Something   # We can cache a value we know only needs to be calculated once like this, and since  # there are implied returns, we get back that same value each time like a cache.  def foo(checked_value)    @foo ||= check_value  end   # But what if we have a method to calculate it? Surely encapsulating it in another  # method is tedious. Well that's what lambdas are for, anonymous functions!  def bar(checked_value)    @bar ||= -> (arg) {      do_something_here(arg)    }.call(checked_value)  endend
Ruby is a marvelous language when you remember it's part functional as well as OO. Make sure to learn the entire Enumerable library, especially the functions map, reduce, find, and select. Speaking of which, a few things I've noticed in newer Ruby programmers code that could be much more concise:

# Badcollection = []other_collection.each { |item| collection << item if condition } # Goodcollection = other_collection.select { |item| condition } # Badcollection = []other_collection.each { |item| collection << do_something_with(item) } # Goodcollection = other_collection.map { |item| do_something_with(item) } # Badpeoples_names = []people.each { |person| peoples_names << person.name } # Betterpeoples_names = people.map { |person| person.name } # Best - there's a shorthand for plucking things with map. Look up symbol to proc,# but be warned it's a long read for newer people.peoples_names = people.map(&:name) # Bad - mutation, and this can be far more concisetotal = 0collection.each { |item| total += item } # Better - I'm being verbose on this one# Say the collection is [1,2,3]. We're reducing it to one number with an initial value of 0,# and the accumulator is passed in to each iteration of the block from the last return value.# Since ruby has implied returns, the accumulator will have the values: 0, 1, 3 and return finally with 6total = collection.reduce(0) { |accumulator, item| accumulator + item } # Best - but again, verbose. Notice the lack of & here, that's unique to operators and is the same with the others for reducetotal = collection.reduce🙂+)
Well that was a fun wall of text, but definitely use those more often. Leads to a lot cleaner code and less surprises later.
I've used this in lazy loading before

Code:
if @some_field.nil?  # do a bunch of parsing and then...  @some_field = falseend
Any suggestions? Because nil is naturally falsy, and I'm handling a boolean here...
Since nil is considered as false within conditions anyway I often stay with the implicit initialization value instead of explicitely changing it to false. However, that actually could cause problems of course, especially if the user is not aware of it.

In other cases I usually use defined? to check if the variable has been used yet (which also allows to store nil values):

def some_field

  @some_field = true  unless defined?(@some_field)

  @some_field

end
Since nil is considered as false within conditions anyway I often stay with the implicit initialization value instead of explicitely changing it to false. However, that actually could cause problems of course, especially if the user is not aware of it.

In other cases I usually use defined? to check if the variable has been used yet (which also allows to store nil values):

def some_field

  @some_field = true  unless defined?(@some_field)

  @some_field

end
Really you could still just use ||= anyways in most cases. I tend to want something to continue until true or otherwise like that so it works out well for me on occasion.
One of the big things that drives me up a wall are people that do something like this:# Bad - Hanging Indentationsome_method.with.a_longer.chain🙂parameter_1,                                😛arameter_2,                                😛arameter_3,                                😛arameter_4) # Good - Drop to a new linesome_method.with.a_longer.chain(  😛arameter_1,  😛arameter_2,  😛arameter_3,  😛arameter_4)but that comes down to stylistic quibbles more than anything.
It's not only a question of stylistic quibbles. One format supports refactoring better than the other.

Say for example we want to change some_method to some_tricky_method because it better captures what the method does.

# Bad - Hanging Indentationsome_tricky_method.with.a_longer.chain🙂parameter_1,                                😛arameter_2,                                😛arameter_3,                                😛arameter_4) # Good - Drop to a new linesome_tricky_method.with.a_longer.chain(  😛arameter_1,  😛arameter_2,  😛arameter_3,  😛arameter_4)
Suddenly we have do conscious work to fix the hanging indentation. D:
Granted. Now a few other things I've seen from reading through scripts around here:

# Badcase valuewhen 'a'; 1when 'b'; 2end # Goodcase valuewhen 'a' then 1when 'b' then 2end # Badcase valuewhen 'a' then x = 1when 'b' then x = 2end # Goodx = case valuewhen 'a' then 1when 'b' then 2end # Badif something == trueif something.nil?if something != true # Goodif somethingunless somethingunless something # Badif x < 100 || x >= 0 # Goodif (0...100).include?(x) # Bad BAD BAD BAD BAD$variable
On another topic, modules and classes.

Modules are for two things:
* Namespacing code

* Abstracting common elements (see Enumerable in Ruby)

Classes are for encapsulating data, like People, Places, or Things

Code:
# Bad - how common is Person as a name? It's in the global namespace.class Person # Good - Namespace it with your alias or something to prevent collisionsmodule Lemur  class Person
Granted. Now a few other things I've seen from reading through scripts around here:

# Badif something == trueif something.nil?if something != true # Goodif somethingunless somethingunless something # Badif x < 100 || x >= 0 # Goodif (0...100).include?(x) # Bad BAD BAD BAD BAD$variable
I don't agree with these at all.

In #1 the bad case is actually better, as it's more explicit about what you're expecting. It's also more correct, as there's code that will cause the "good" case to fail that won't fail in the "bad" case. You should be as explicit as you can about what you're trying to do and avoid checks that are more general than necessary.

On #2 those are checking separate things. If you make them equivalent, so it reads:

if x >= 0 && x < 100 if (0...100).include?(x)The first case is also better as it's more explicit about your expectations, doesn't require you to remember the properties of the horribly ambiguous ".." vs "..." operators and doesn't use the less efficient .include? check.

#3 globals aren't inherently bad. They have a time and a place, like anything else.
Avoid to call double Sprite.new or Bitmap.new instance in same method  : spare your sprite instance in different method this make the whole method more readable and avoid the Sprite drawing lag

EDIT: I speak by experience by using a lot of sprite in same time this obvious this will have lag..this sprite drawing so...

but I noticed when you put them into the same method...they have horrible lags 

but after when you cut them into multiple method..the lag was still here but less present and the script was running more smoothly

#BAD

def something@sprite1 = Sprite.new#blabla sprite cordinate@sprite2 = Sprite.new#blabla again [email protected] = Sprite.newend# will result to a big reduce of efficiency good way!

Code:
def something_1@sprite = Sprite.new#stuffenddef something_2@sprite2 = Sprite.new#stuff2end#ect
This is purely syntactical, but indenting your attribute setting calls properly does a lot for readability. Consider the following standard indentation:

def setup_font @font = Font.new("VL PGothic", 18) @font.color = Color.new(44, 44, 44, 255) @font.outline = true @font.out_color = Color.new(245,245,245,255) @font.shadow = falseendNow with assignment indentation:

def setup_font @font = Font.new("VL PGothic", 18) @font.color = Color.new(44, 44, 44, 255) @font.outline = true @font.out_color = Color.new(245,245,245,255) @font.shadow = falseendNow, the only issue with this is that it's hard to do manually. But most (good) code editors have plugins for this, like Vim or Sublime Text 3 🙂
I don't agree with these at all.

In #1 the bad case is actually better, as it's more explicit about what you're expecting. It's also more correct, as there's code that will cause the "good" case to fail that won't fail in the "bad" case. You should be as explicit as you can about what you're trying to do and avoid checks that are more general than necessary.

On #2 those are checking separate things. If you make them equivalent, so it reads:

if x >= 0 && x < 100 if (0...100).include?(x)The first case is also better as it's more explicit about your expectations, doesn't require you to remember the properties of the horribly ambiguous ".." vs "..." operators and doesn't use the less efficient .include? check.

#3 globals aren't inherently bad. They have a time and a place, like anything else.
#1 - Then you haven't been in dynamic languages for very long. Inferring things is far more preferred. 

#2 - Sleep deprivation does bad things. Other than that:

[4] pry(main)> Benchmark.measure { 100.times { x >= 0 && x < 100 }}.real=> 8.0e-06[5] pry(main)> Benchmark.measure { 100.times { (0...100).include?(x) }}.real=> 2.4e-05[6] pry(main)> Benchmark.measure { 1000000.times { x >= 0 && x < 100 }}.real=> 0.054781[7] pry(main)> Benchmark.measure { 1000000.times { (0...100).include?(x) }}.real=> 0.147749 [8] pry(main)> Benchmark.measure { (0...100).include?(x) }.real=> 3.0e-06[9] pry(main)> Benchmark.measure { x >= 0 && x < 100 }.real=> 3.0e-06
It is, but if you're really noticing that type of speed hit you probably should not use Ruby.

#3 They do, but the amount that people use them on here it's better to consider them inherently bad for newbies. I haven't had to use one once in the past 2 years, it's normally just bad design. As soon as you find a good reason for them, it's fine to use, but those are extremely rare. It's like the english and and or operators, best general rule is just to not use them.
I concur with Lemur here that global variables should be considered inherently bad, period. There is actually no reason ever to use a global variable when you write scripts; if you need it, put static variables in your module, and call them like this:

YourModule::STATIC_VARBut even that is semi-decent. The preferred way should be:

Code:
module TDD  module Settings    class << self # <- All methods within this are self methods      def global_width        return Graphics.width - 30 # <- Of course it could be a static number too, but with methods you can perform computations      end    end  endend# Call itputs TDD::Settings.global_width
#1 Doesn't matter what language you're working in, clarity and readability is always extremely important, especially if anyone other than yourself will ever have to look at or modify the code. Explicit logic is always preferred to implicit logic. Good programming is not about saving keystrokes, it's about saving code maintenance time.

#2 It's not necessarily about optimizing performance, it's about not using a more complicated code path for no good reason. There's not a huge performance hit for declaring extra variables you don't need or checking conditions you don't need to check, but it's still bad practice to do it. It does more work, it doesn't actually give you any benefit and it's less clear than explicitly checking for the conditions you actually want.
#1 Doesn't matter what language you're working in, clarity and readability is always extremely important, especially if anyone other than yourself will ever have to look at or modify the code. Explicit logic is always preferred to implicit logic. Good programming is not about saving keystrokes, it's about saving code maintenance time.

#2 It's not necessarily about optimizing performance, it's about not using a more complicated code path for no good reason. There's not a huge performance hit for declaring extra variables you don't need or checking conditions you don't need to check, but it's still bad practice to do it. It does more work, it doesn't actually give you any benefit and it's less clear than explicitly checking for the conditions you actually want.
Then you and I will heavily disagree. To me, who's worked in Ruby for 3+ years, ranges are far clearer and implied values are trivial to understand.

It's common in Javascript, Perl, Python, and other dynamic languages to have a concept of truthy and falsy values. That's not unclear, that's just spending too much time in Java or C languages and forcing habits onto Ruby.

Treat Ruby like Ruby, not another language. That's your mistake. Read community code, find a few open source projects with high code climate scores. They do the exact same things. This is from the opinion of someone who's been in the Ruby community, not a Java or C programmer.

Edit -

Almost forgot, almost all functional languages behave the same way as well. Don't forget Ruby inherits a lot from LISP as well.
All of those are just personal preference I think. It just like debating which is right

This

if (condition) { # Statements}Or this

if (condition){ # Statements}Or even this

if (condition) {}I personally like to discuss such as how to avoid incompatibilities among various script instead of how properly to write in Ruby since hey, this is "Coding the RM way". Don't get me wrong, I enjoy your lecture, but honestly I don't like a person uses his experience (saying I'm 10 years experience on these things) to blame others and take this so serious.

If someone refuse to accept your lecture, then it's their choice.
Quote from Trickster, posted by PK8:

The only global variables that should be added are new $data_ and $game_ objects.
Instead of creating new $game_... - Variables, I prefer adding new game objects to the existing ones (especially Game_System), so creation, serialization, deserialization and whatever users might further do with the entire game object set is covered automatically (besides an accessor method is more flexible than a global variable 🙂 ):

How it is done often:

class << DataManager   alias_method🙂create_game_objects_ILC_addQuestlog, :create_game_objects)  def create_game_objects    create_game_objects_ILC_addQuestlog    $game_questlog = Game_Questlog.new  # Create Questlog on "New Game"  end   alias_method🙂make_save_contents_ILC_addQuestlog, :make_save_contents)  def make_save_contents    make_save_contents_ILC_addQuestlog.tap do |contents|      contents[:questlog] = $game_questlog  # Save Questlog    end  end   alias_method🙂extract_save_contents_ILC_addQuestlog, :extract_save_contents)  def extract_save_contents(contents)    make_save_contents_ILC_addQuestlog(contents)    $game_questlog = contents[:questlog] || Game_Questlog.new  # Load Questlog  endendHow it could be done instead:

Code:
class Game_System   def questlog    @questlog ||= Game_Questlog.new  endend
The most critical advice I can give is not to treat Ruby like Java, C#, or whatever other language you're used to. Ruby should be written in the style of Ruby, and if you want to learn it then learn that.

Ruby is a descendant of Smalltalk, Perl, and LISP. While there are others, those tend to be the most prominent.

Honestly some of the worst Ruby I've seen comes from Java programmers who insist on treating Ruby like freeform Java. The amount of time I have to spend cleaning up after their messes after that is annoying, they're dead set on treating it like Java.
Then the java programmers have the advantage of understanding "Java Style" Ruby while the Ruby programmers only see them as messed up.

Also one thing that should be noted as well. Probably it's only me though, but dunno.

There's a maximum character for each line. If it goes to long, break them down. Having long line for comment, instruction, or code itself is bad. You can not see the whole code and need to scroll it to the right. Default scripts, Yanfly scripts, and my script did this. However, I usually see many scripters didn't do this.
Then the java programmers have the advantage of understanding "Java Style" Ruby while the Ruby programmers only see them as messed up.
That, assuming that they have an even marginally consistent style. Some only dip their toes while others try swimming, it's all over the place. What's worse is frequently the level they commit to 'The Ruby Way' is so variable it makes an incomprehensible mess out of everything leaving micro-frameworks every other file and completely different styles. If you're going to use a language, immerse yourself fully in its community and its culture.

When one wields a sword, they would be a fool to grip the blade and swing it as if it were a quarterstaff. More appropriately, treating a sword as a dagger, or a quarterstaff as an ashandarei would be a bad idea. You would injure yourself or others. In the case of programming, you end up making other coders that have to work on your code spend hours deciphering what you've done and cleaning it up. It's a good way to make enemies real fast. Always assume the next person to touch your code is a psychopathic madman with an incredibly short temper who knows where you live.

I don't pretend you're going to listen on that, and yes I mention I have experience in the field because it's relevant. I know what happens when you don't. If you choose to see that as me throwing rank, so be it, but it would be a fools move. I've learned from experience it's a bad idea to treat any language like another language.

As far as the notion of implications and avoiding explicit information, it's a concept of reasonable inference present in many functional languages such as Haskell, Scala, Clojure, Lisp, Livescript, and Elixer/Erlang among many many others. Languages like Java and C# do not have this concept at the forefront, as it's normally descendant of first class functions. What's funny is that Haskell is even more strongly typed than the others despite what it can infer (Hindley Milner typesystem)

I won't lie to you, thinking in a functional language is a mind-bender if you've only been on the imperative end (Java/C) but it will lead to substantially more robust code by thinking that way. Pure functional programming (Haskell) involves no mutation of variables, that means everything is final. Ruby is a hybrid, but leveraging this as much as possible is of great benefit.

Now some may cry foul on encouraging FP, saying that's the same as treating Ruby like Java. No, you're learning a paradigm of thinking rather than a languages notions.

Now as far as how to learn some of it, tutorials for Ruby might include:

If you want to understand it in pure form, Learn you a Haskell will be a mind-warp of a read.

TL;DR Treat Ruby like Ruby or you'll have a bad time. Remember Ruby is part Functional, you should totally learn that part of it too.

Original thread: https://forums.rpgmakerweb.com/threads/coding-the-rm-way.25081/