Re:Ask HN: What does Ruby have that Python doesn't?
by kashif on Friday August 22, 2008 @04:28PM
(#284148)
Then use a function with some introspection and pass it some parameters.
[ Parent
| on HN ]
Re:Ask HN: What does Ruby have that Python doesn't?
by cturner on Friday August 22, 2008 @06:56PM
(#284288)
You can but you shouldn't need to. Sometimes I want to do something like:
dict['item'] = def _(var1, var2):
fn_var = 1
do_some_magic(fn_var, var1, var2)
There's no good reason why I should instead have to do: def fn(var1, var2):
blah
dict['item'] = fn
.. or write a decorator.I'm frequently tempted to write a python-like scheme syntax to sit in my python programs so I can just do this stuff and to hell with the excuses used to prevent my first code block from above from working.
Re:Ask HN: What does Ruby have that Python doesn't?
by LogicHoleFlaw on Saturday August 23, 2008 @03:21PM
(#284775)
It's been a while since I wrote any Python but... here's a shot in Lua.
Lua:
function dict.item (var1, var2)
local fn_var = 1
do_some_magic(fn_var, var1, var2)
end
-- note that:
function dict.item (arg) return arg end
-- is syntax sugar for:
dict.item = function (arg) return arg end
-- for an implicit "self" parameter use a : in your declaration and invocations:
function dict:item (arg) return self(arg) end
-- is sugar for
dict.item = function (self, arg) return self(arg) end
You can in fact call functions with the implicit (via :) self parameter with any desired "self" by using the "." rather than ":" invocation syntax and providing an explicit self. ":" is purely sugar which is optional in all cases. function table:swap()
local swapped = {}
for k, v in pairs(self) do
swapped[v] = k
end
return swapped
end
-- assume "Table()" returns a table which routes "method_missing" calls
-- (which is actually the __index metamethod in Lua)
-- to `table`
t = Table { a = "foo", b = "bar" }
a = t:swap()
b = table.swap(t)
-- a and b are both equal to:
-- { foo = "a", "bar" = b }
One neat thing about Lua is that the user can define basically arbitrary semantics for inheritance, mixins, and all sorts of meta stuff very simply. And you can define them on a per-object basis. It's very powerful. The drawback is that you have to implement these things yourself (unless you use a 3rd-party lib which provides some common patterns like you'd see in Python or Ruby).
Re:Ask HN: What does Ruby have that Python doesn't?
by cturner on Thursday August 28, 2008 @02:45AM
(#288931)
Thanks for that. I've looked at io a bit, which is similar to lua, and been very impressed by stuff like this. Also that you can effectively reflect against function definitions in order to create modified versions at a later time.