4 ms·
There are two things that Ruby has that Python doesn't have a good syntax for. One is blocks; in Ruby, I can write: foo { |x| puts x } Whilst in Python, I
by weavejester 16y ago
There are two things that Ruby has that Python doesn't have a good syntax for. One is blocks; in Ruby, I can write:
foo { |x| puts x }
Whilst in Python, I need to write:
def tmp(x): print x
foo(tmp)
It's not really very nice.
The other thing is that Python has no concept of context. In Ruby, I can type:
foo(x)
And it will execute foo(x) for the containing object. In Python, the closest equivalent would be:
self.foo(x)
This syntax difference may seem trivial, but it allows you to do some very interesting things to classes. For instance:
class Foo
def self.property(name)
define_method(name) do
instance_variable_get(name)
end
end
end
class Bar < Foo
property :x
end
Now the class Bar has a method called "x", without us needing to explicitly define it.
Ruby's instance_eval method extends this further, allowing you to execute a block of code in the context of any object you wish.
- llimllib 16y ago> The other thing is that Python has no concept of context Rather, I'd say that part of the zen of python is: implicit is better than explicit, and I prefer python's behavior in this instance.
- nuclear_eclipse 16y agoYou've got that backwards for Python: Explicit is better than implicit.
- llimllib 16y agodoh!
- etal 16y agoNot disagreeing with you. In fact, the first example is one reason why "print" was changed from a keyword to a function in Python 3: myfunc <- lambda x: (print x) or x*x # SyntaxError myfunc <- lambda x: print(x) or x*x # OK in Py3