红宝石 |构造 to_s()函数
to_s()是 Ruby 中的一个内置方法,它返回一个带有特定结构值的字符串。
Syntax: struct_name.to_s()
Parameters: The function does not accepts any parameter.
Return Value: It returns the value of struct.
示例 1 :
# Ruby program for to_s method in struct
# Include struct
animals = Struct.new(:name, :speciality , :found_in)
# initialize values
detail = animals.new("labrador", "bark" , "Newfoundland")
# to_s used
puts detail.to_s
输出:
struct name="labrador", speciality="bark", found_in="Newfoundland"
示例 2 :
# Ruby program for to_s method in struct
# Include struct
animals = Struct.new(:name)
#initialize values
detail = animals.new("golden retriever")
#to_s used
puts detail.to_s
输出:
struct name="golden retriever"