SoFunction
Updated on 2024-10-30

Comparing the Programming Differences between Python and Ruby via for Loops

Preface.

Much of the difference between Ruby and Python can be seen in the nature of the for loop, where Python has a for statement. Python has the for statement, where the object tells the for how to work, and the for loop takes care of what the object returns. In Ruby, the for itself (via each) is a method of the object. The caller passes the body of the for loop to this method. In Python's language conventions, the object model obeys the for loop. In Ruby, for loops obey the object model.

That is, in Python, if you want to customize the iteration process, you can have the object tell the interpreter how to iterate:

class Stuff:
    def __init__(self):
        self.a_list = [1,2,3,4]
         = 0
    def __next__(self):
        try:
            value = self.a_list[]
             += 1
            return value
        except IndexError:
             = 0
            raise StopIteration
    def __iter__(self):
        return self

Here, Stuff usesnext cap (a poem)iter The magic method makes itself iterable (it becomes an iterable object).

for data in Stuff():
    print(data)

However, in Ruby's usage, you do the opposite. You create for as a method that receives code (the body body) to run. ruby puts procedure codes in blocks of code so they can be used for passing.

Then, in the each method, use yield to interact with the code block, passing the value to the code block to do what you need to do (the code block is an implicit parameter for any method).

If we rewrite the code above, it will look like this:

class Stuff
  def initialize
    @a_list = [1, 2, 3, 4]
  end
  def each
    for item in @a_list
      yield item
    end
  end
end

Iterate using each:

().each do |item|
  puts item
end

Instead of passing data to a for loop (Python), the loop code is passed to the data (Ruby).

But the difference goes much further:

Python builds for-like structures for all kinds of processing; Ruby puts the data processing into methods.

Great Python code uses lists and dictionary parsers formapcap (a poem)filter, the core of these expressions is the same as the semantics of for/iteration.

In [2]: [item for item in Stuff()]
Out[2]: [1, 2, 3, 4]
In [3]: [item for item in Stuff() if item % 2 == 0]
Out[3]: [2, 4]

Ruby continues to use a method-first approach, and in addition to the each method, there are a number of new methods that are commonly used for working with collections.As shown below:

class Stuff
  ...
  def select
    out = []
    each do |e|
      # If block returns truthy on e, append to out
      if yield(e)
        out << e
      end
    end
    out
  end
  def map
    out = []
    # One line block syntax, append output of block processed on e to out
    each {|e| out << yield(e) } 
    out
end
puts ().map {|item| item}
puts ().select{|item| ?}

Python said:"You tell us how to iterate over your instances, and we'll decide what to do with your data." Python has some language-based primitives used as iteration and processing, so to customize the iteration, just add the right code to the for loop body (or expression).

Ruby reverses the script and gives objects deeper customizability. Yes, in some cases we can add more control flow to a block of code, and yes, we can use the each method as a map. Yes, we can use the each method as a map, but Ruby allows objects to implement map and each differently (it can be very undesirable and even unsafe to use the "each" implementation for "map"). Ruby objects have better ways of handling their data.

In Ruby, objects control functional visibility. In Python, it's the syntax that controls.

Authentic Python has a strong view of data processing. python says, "Look, 90% of code incorporates these ideas well, just follow it and get the job done." Make your objects for-loopable and stop bugging me.

However Ruby said:"In some important cases, we don't want to give the caller too much power." So Ruby lets objects control the way they are handled, and requires developers to follow the way objects want to be interacted with.Ruby isn't that strong on data handling.

Python is more of an extension of C-based "object-oriented" programming. In C-based OO, like posix file descriptors or Win32 window handles, the language doesn't force "methods" to be bound to the objects themselves. Instead, the binding of objects to methods is based on convention.

Python thinks that the process world can evolve - it upgrades that way of thinking to make it safer. Free functions exist (PythonCat's note: this should refer to built-in functions, which are "free" because they don't depend on any class object), and are indeed often preferred over object methods. Objects exist, but in a relatively hesitant way.

Class methods accept "self" as their first argument, almost in the same way that C functions in the Win32 or Posix APIs accept handles. When functions are passed, they are treated almost like C function pointers.

Python considers the procedural paradigm to be the most important, it's the key foundation for everything, and on top of it is the object-oriented semantic layer.

Ruby, however, turns this on its head.Ruby uses object-orientation as the foundation of the pyramid.Ruby includes the messy world of procedures in blocks of code, and lets objects use those blocks.

Instead of destroying objects in order to follow the procedural foundations of the language, Ruby adapts procedural code to the object view of the world. ruby has truly private methods, unlike Python's private methods/arguments, which are just out of convention.

There's no doubt that when I approached Python from a systems programming perspective, it was a natural fit for my outlook. Equipped with the ability to write C when necessary, it evolved to make that world safer. Perhaps that's why it has found a place in the resource-intensive world of numerical computation.

It's no wonder that Ruby is well suited for developers to build smoother, and perhaps safer, APIs and DSLs.Ruby expects programmers to model the domain, not the programming environment, and that seems to be the right approach for a lot of work.

To this point, this article on the for loop comparison of Python and Ruby programming differences between the article is introduced to this, more related to Python and Ruby content, please search for my previous articles or continue to browse the following related articles I hope you will support me more in the future!