Honestly not really like to discuss Ruby and Python contrast, it seems to always put two languages in the opposite position, I think it is not necessary, the same dynamic language, also is the interpretation of scripting language, many features are mutual influence, the language itself is constantly evolving, We should pay more attention to the idea of programming rather than the language itself.
Said a little off-topic, the reason why asked to learn Ruby, is mainly because there is a good book to read, is Paolo Perrotta "Ruby Meta-Programming", the book read a day, Ruby Grammar for half a day, with IRB tinkering with a night, should say with Python, Scala has a lot of similarities because it doesn't have access to functional programming languages like Lisp,haskell, so it's hard to say how it is with them, but it's very easy to learn python and learn Ruby.
In the book in Tuesday, there is a problem challenge, is the DS and computer classes in the dynamic generation of functions, well, I made the same thing, the book half, I do first, after seeing the Define_method method with my own idea of a solution, have not read the example, Let's take a look at the code first, and here's my first Ruby program:
# Data source definition. It should be an associated database, here is just a simulation
class DS
parts = ‘cpu’, ‘mouse’, ‘keyboard’ # temporary arrays are used for batch generation methods
parts.each do | part |
define_method "get _ # {part} _info" .to_sym do | id | # Generate info function for three devices
"This is # {part} # {id}."
end
define_method "get _ # {part} _price" .to_sym do | id | # Generate price function for three devices
parts.zip ([150, 50, 40]). to_h [part] # Combine the array into a hash structure and index it by zip
end
end
end
# Computer accessories definition
class Computer
def initialize (computer_id, data_source) # Initialize id and data source
@id = computer_id
@data_source = data_source
end
parts = ‘cpu’, ‘mouse’, ‘keyboard’
parts.each do | part |
define_method part.to_sym do
info = @ data_source.send ("get _ # {part} _info" .to_sym, @id)
price = @ data_source.send ("get _ # {part} _price" .to_sym, @id)
result = "# {info} ($ # {price})"
return "* # {result}" if price> = 100 # determine whether the price is higher than 100, with an asterisk displayed
result
end
end
end
puts "DS methods: # {DS.instance_methods (false)}"
puts "Computer methods: # {Computer.instance_methods (false)}"
ds = DS.new
computer = Computer.new (10, ds)
puts computer.cpu
puts computer.mouse
puts computer.keyboard
The first Ruby program