当前位置: 动力学知识库 > 问答 > 编程问答 >

it's correct create multiple classes in ruby?

问题描述:

Hi i have a question because i usually use multiple classes in Ruby but i dont know if is that correct?, for example the next code:

Class Main.rb

class Main

require_relative 'Archivo.rb'

require_relative 'Diccionario.rb'

require_relative 'Jsn.rb'

hsh = Diccionario.new

jsn = Jsn.new

fl = Archivo.new

puts "Ingresa Nombre"

nombre = gets

puts "Ingresa Correo"

correo = gets

puts "Ingresa password"

password = gets

hsh.usuario(nombre,correo,password)

jsn.convert_json(hsh.get_usuario)

fl.write('usuario.json',jsn.get_json)

fl.read('usuario.json')

puts fl.get_line

end

Class Diccionario.rb in other file

class Diccionario

$usuarios = Hash.new

require 'json'

def usuario(nombre, correo, password)

$usuarios = {nombre: nombre, correo: correo, password: password}

end

def get_usuario

$usuarios

end

end

Class Jsn.rb in other file

class Jsn

require 'json'

$cadena

def convert_json(cadena)

$cadena = cadena.to_json

end

def get_json

$cadena

end

end

Class Archivo.rb in other file

class Archivo

$line

def read(file)

File.open(file,"r") {|archivo|

$line =archivo.gets

}

end

def write(file,cadena)

File.open(file, "w+") do |f|

f.puts cadena

end

end

def get_line()

$line.to_s

end

end

Thanks :D

网友答案:

You should definitely be creating multiple classes! I would try to think in terms of SOLID principles to ascertain where behaviour belongs and which objects/classes have responsibility for implementing them.

There's an excellent book called Practical Object Oriented Design in Ruby by Sandi Metz. It's a great book about how to organise your code into classes. It talks about SRP (Single Responsibility Principle) and how to drill down to the essence of the problem you're trying to solve. If you can't buy the book then there's a talk that covers the main points here:

https://www.youtube.com/watch?v=8bZh5LMaSmE

She actually mentions that it's a common error to "not create enough classes" and that you should feel confident to break the implementation down further to smaller manageable classes.

分享给朋友:
您可能感兴趣的文章:
随机阅读: