我在构造to_s方法时遇到了问题。
class Personne
attr_accessor :prenom, :nom, :email, :telephone, :adresse
def initialize
@prenom = @nom = @email = @telephone = ""
@adresse = Adresse.new
end
def to_s
@prenom + ", " + @nom + "\n" + \
"Email: " + @email + "\n" + \
"Tel: " + @telephone + "\n" + \
@adresse
end
end
@adresse是和非常相似的to_s方法的对象。 错误:
in `+': no implicit conversion of Adresse into String (TypeError)
我不明白这个问题,因为地址对象有自己的打印方法。
答案 0 :(得分:0)
我不明白这个问题,因为地址对象有它自己的打印 方法
您正在将类soundarya@soundarya-VirtualBox:~/Downloads/elasticsearch-2.4.0/bin$ curl -XGET 'http://localhost:9200/aida/_search' -d '{
"query":{
"match":{
"text":"My"
}
}
}'
的实例作为参数传递给soundarya@soundarya-VirtualBox:~/Downloads/elasticsearch-2.4.0/bin$ curl -XGET 'http://localhost:9200/aida/_search' -d '{
"query":{
"match":{
"text":"my"
}
}
}'
{"took":5,"timed_out":false,"_shards":{"total":5,"successful":5,"failed":0},"hits":{"total":0,"max_score":null,"hits":[]}}
方法,在字符串上调用,它会抛出错误,因为它期望String类的实例作为参数
要完成这项工作,您可能希望使用例如 imageView.setDrawingCacheEnabled(true);
Bitmap bitmap = imageView.getDrawingCache();
File root = Environment.getExternalStorageDirectory();
File cachePath = new File(root.getAbsolutePath() + "/DCIM/Camera/image.jpg");
try {
cachePath.createNewFile();
FileOutputStream ostream = new FileOutputStream(cachePath);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, ostream);
ostream.close();
} catch (Exception e) {
e.printStackTrace();
}
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("image/*");
share.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(cachePath));
startActivity(Intent.createChooser(share,"Share via"));
方法将其转换为字符串。
Adresse
答案 1 :(得分:0)
some_string + object
不会在对象上触发to_s
。您需要使用字符串插值("#{some_string}#{object}"
)或需要详尽地调用to_s
(some_string + object.to_s
):
class Personne
attr_accessor :prenom, :nom, :email, :telephone, :adresse
def initialize
@prenom = ''
@nom = ''
@email = ''
@telephone = ''
@adresse = Adresse.new
end
def to_s
"#{prenom}, #{nom}\nEmail: #{email}\nTel: #{telephone}\n#{adresse}"
end
end
旁注:@prenom = @nom = @email = @telephone = ""
将所有属性设置为相同的字符串。如果您执行@nom << 'foo'
而非@email
之类的操作也会更改。见这个例子:
foo = bar = ''
foo << 'foo'
#=> "foo"
bar
#=> "foo"
因此我也更改了您的initialize
方法。