Does Ruby Have a String.Startswith("Abc") Built in Method

Does Ruby have a string.startswith(abc) built in method?

It's called String#start_with?, not String#startswith: In Ruby, the names of boolean-ish methods end with ? and the words in method names are separated with an _. On Rails you can use the alias String#starts_with? (note the plural - and note that this method is deprecated). Personally, I'd prefer String#starts_with? over the actual String#start_with?

Ruby creating title case method, can't handle words like McDuff or McComb

There are several issues with your "Mc" code:

if (word.include?("mc"))

This will always return false, because you have already capitalized word. It has to be:

if word.include?('Mc')

This line doesn't work either:

letter_array = word.split!("")

because there is no split! method, just split. There is however no reason to use a character array at all. String#[] allows you to access a string's characters (or sub-strings), so the next line becomes:

if (word[0] == 'M') && (word[1] == 'c')

or just:

if word[0, 2] == 'Mc'

or even better using start_with?:

if word.start_with?('Mc')

In fact, we can replace the first if with this one.

The next line is a bit tricky:

letter_array[2].capitalize!

Using String#[] this becomes:

word[2].capitalize!

But unfortunately, both don't work as expected. This is because [] returns a new object, so the bang method doesn't change the original object. Instead you have to call the element assignment method []=:

word[2] = word[2].upcase

Everything put together:

if word.start_with?('Mc')
word[2] = word[2].upcase
end

Or in a single line:

word[2] = word[2].upcase if word.start_with?('Mc')

How to check whether a string contains a substring in Ruby

You can use the include? method:

my_string = "abcdefg"
if my_string.include? "cde"
puts "String includes 'cde'"
end

Why does Ruby let me call a String method without specifying the string?

Ruby 1.8 has a method Kernel#split([pattern [, limit]]) which is identical to $_.split(pattern, limit), and gets sets the value of $_.

Does ActiveRecord's find method automatically call to_i on its argument?

[Answering this with activerecord-2.3.14code, as you didn't specify a version.]

Ultimately, your value is going to be run through the Quoting#quote method. I've pasted the beginning of that here, and as you can see on the block starting at line 15 when your column type is an int it will end up calling .to_i on the value passed in.

  1 module ActiveRecord
2 module ConnectionAdapters # :nodoc:
3 module Quoting
4 # Quotes the column value to help prevent
5 # {SQL injection attacks}[http://en.wikipedia.org/wiki/SQL_injection].
6 def quote(value, column = nil)
7 # records are quoted as their primary key
8 return value.quoted_id if value.respond_to?(:quoted_id)
9
10 case value
11 when String, ActiveSupport::Multibyte::Chars
12 value = value.to_s
13 if column && column.type == :binary && column.class.respond_to?(:string_to_binary)
14 "'#{quote_string(column.class.string_to_binary(value))}'" # ' (for ruby-mode)
15 elsif column && [:integer, :float].include?(column.type)
16 value = column.type == :integer ? value.to_i : value.to_f
17 value.to_s
18 else
19 "'#{quote_string(value)}'" # ' (for ruby-mode)
20 end

How can I check if a string represents an int, without using try/except?

If you're really just annoyed at using try/excepts all over the place, please just write a helper function:

def RepresentsInt(s):
try:
int(s)
return True
except ValueError:
return False

>>> print RepresentsInt("+123")
True
>>> print RepresentsInt("10.0")
False

It's going to be WAY more code to exactly cover all the strings that Python considers integers. I say just be pythonic on this one.

How does Ruby(or other languages) Implicitly know which object belongs to which built in class?

The concept you're looking for is Literals, but to explain it in more detail, let's start with your example code.

String.new

There are actually two different strings in this code:

x = String.new("Hi")

"Hi" is a string object, and then a second string object is created and stored in x. You can see this better with this equivalent code:

y = "Hi"
x = String.new(y)

The x and y variables hold two different strings objects, even though both objects contain the same contents. You can prove that they are different by modifying one of them, and checking that the other one stays the same

y.downcase!
y #=> "hi"
x #=> "Hi"

Cat.new

Considering this code:

jinx = Cat.new("Jinx")

When you say that "Jinx" is a Cat, that's not quite right. "Jinx" is still a string. Cat.new will create a new Cat object, and it will store the "Jinx" string inside the object.

You can see the difference more clearly like this:

# this is a string
name = "Jinx"
name.length #=> 4

# this is a Cat, with a string inside it
jinx = Cat.new(name)
jinx.name #=> "Jinx"
jinx.name.length => 4

The Difference

The difference between the two is that Ruby has string literals but not Cat literals.

A literal is an object that you can type into code, without actually creating it with new. Here are some examples of literals:

  • "Hello" makes a String object
  • 5 makes an Integer object
  • 5.5 makes a Float object
  • [] makes an Array object
  • {} makes a Hash object

You can see a full list of Ruby literals here: https://ruby-doc.org/core-2.3.0/doc/syntax/literals_rdoc.html

There is no literal for Cat objects, because it's a custom class you created youself. I can't just type in something like <Jinx> to create a Cat object because Ruby will not understand that -- I have to create it with Cat.new.



Related Topics



Leave a reply



Submit