Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/ms-access/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 使用RubyonRails进行字符串操作_Ruby On Rails_String - Fatal编程技术网

Ruby on rails 使用RubyonRails进行字符串操作

Ruby on rails 使用RubyonRails进行字符串操作,ruby-on-rails,string,Ruby On Rails,String,我一直在尝试操作字符串(如java中的子字符串函数) 因此,大多数在线指南指向以下选项: str.split("A").first str[0...15] str.from(0).to(15) 但每当我使用上述任何一种方法时,我都会出现以下错误: 命名者 1) undefined method 'split' 2) undefined method '[]' 3) undefined method 'from' 我想我应该使用一些lib或其他东西。任何朝着正确方向的帮助

我一直在尝试操作字符串(如java中的子字符串函数) 因此,大多数在线指南指向以下选项:

   str.split("A").first
   str[0...15]
   str.from(0).to(15)
但每当我使用上述任何一种方法时,我都会出现以下错误:

命名者

1) undefined method 'split'

2) undefined method '[]'

3) undefined method 'from'
我想我应该使用一些lib或其他东西。任何朝着正确方向的帮助都将不胜感激


注意:使用ruby 2.0和rails 4来执行字符串操作,您需要一个
字符串
对象,而不是其他对象:

str = 'this is string'
#=> "this is string"
str.split("i").first
#=> "th"
 str[0...5]
#=> "this "
字符串上没有从
/
方法,您可以使用
[]

如果需要将对象强制转换为字符串,则有一个方法

编辑 要将有效的日期字符串转换为
DateTime
对象,请使用:

要使用其演示文稿,请使用:


它是mysql数据库结果的一部分。我得到的日期时间是“2015-04-28014:54:45.000Z”。我想是时区的问题。基本上,date=(result.created_date).split(T).first或date=result.created_date[0…15]会给我一个无方法错误,我希望结果是smthg,如:“YYYY-MM-DD hh;MM:ss”你能展示你所做的全部事情吗?当你从数据库获取字符串时,你如何分配
str
变量?确保
str
是一个字符串。如果您能显示
str
的值就好了。我猜str不是字符串,而是日期对象。当你打印一个日期对象时,它会显示一个类似日期的字符串,但是rails足够聪明,可以将日期转换成实际的DateTime对象(不是字符串,有不同的方法)>所以。。。你到底想用这个字符串做什么?你是想提取日期的某个特定部分吗?也许您应该尝试查找执行该操作的Date方法,并在“str”变量上尝试它?(并且可能重命名变量)
"2015-04-28T14:54:45.000Z".to_datetime
#=> Tue, 28 Apr 2015 14:54:45 +0000
"2015-04-28T14:54:45.000Z".to_datetime.strftime("%Y-%m-%d %H:%M:%S")
#=> "2015-04-28 14:54:45"